#include "bit_stuff.h"
#include <limits.h>
#include <stddef.h>

// leave resource_detector.h as last include!
#include "resource_detector.h"

unsigned int count_ones(unsigned int value){
    unsigned int count = 0;
    while (value){
        count += value & 1;
        value >>= 1;
    }
    return count;
}

void make_bitmask(unsigned int width, unsigned int shift, unsigned int* mask){
    if (width == 0 || width > sizeof(unsigned int)*CHAR_BIT) return; 
    if (width == sizeof(unsigned int) * CHAR_BIT) *mask = ~0U << shift;
    else *mask = ((1U << width) - 1) << shift;
}

void apply_bitmask(unsigned int value, unsigned int mask, unsigned int* masked_value) {
    if (masked_value != NULL) {
        *masked_value = value & mask;
    }
}

void flip_bit(unsigned int value, unsigned int bit_index, unsigned int* updated_value){

    if (updated_value == 0 || bit_index >= sizeof(unsigned int) * CHAR_BIT) return;
    *updated_value = value ^ (1U << bit_index);
}

void extract_nibbles_from_byte(uint8_t value, uint8_t* high_nibble, uint8_t* low_nibble){
    if (high_nibble == NULL || low_nibble == NULL) return;
    *high_nibble = (value >> 4) & 0xF;
    *low_nibble = value & 0xF;
}

void combine_nibles_to_byte(uint8_t high_nibble, uint8_t low_nibble, uint8_t* value){
    if (value == NULL) return;
    *value = (high_nibble << 4) | (low_nibble);
}