/* Copyright (C) 2015-2021, Dirk Krause SPDX-License-Identifier: BSD-3-Clause */ /* WARNING: This file was generated by the dkct program (see http://dktools.sourceforge.net/ for details). Changes you make here will be lost if dkct is run again! You should modify the original source and run dkct on it. Original source: dk4bf.ctr */ /** @file dk4bf.c The dk4bf module. */ #include "dk4conf.h" #if DK4_HAVE_ASSERT_H #ifndef ASSERT_H_INCLUDED #include #define ASSERT_H_INCLUDED 1 #endif #endif #include #include /** Position of single bits within a byte. */ static const unsigned char dk4bf_bits_in_byte[] = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 }; dk4_bit_field_t * dk4bf_open(size_t sz, dk4_er_t *erp) { dk4_bit_field_t *back = NULL; size_t bsz; #if DK4_USE_ASSERT assert(0 < sz); #endif if (0 < sz) { back = dk4mem_new(dk4_bit_field_t,1,erp); if (NULL != back) { back->s = sz; bsz = sz / 8; if (0 != (sz % 8)) { bsz++; } back->d = dk4mem_new(unsigned char,bsz,erp); if (NULL == back->d) { dk4bf_close(back); back = NULL; } } } else { dk4error_set_simple_error_code(erp, DK4_E_INVALID_ARGUMENTS); } return back; } int dk4bf_set(dk4_bit_field_t *dptr, size_t bitno, int val, dk4_er_t *erp) { size_t bytei; /* Byte index */ size_t biti; /* Bit index */ int back = 0; #if DK4_USE_ASSERT assert(NULL != dptr); #endif if (NULL != dptr) { if (bitno < dptr->s) { bytei = bitno / 8; biti = bitno % 8; if (0 != val) { (dptr->d)[bytei] |= dk4bf_bits_in_byte[biti]; } else { #if VERSION_BEFORE_20210729 (dptr->d)[bytei] &= (~(dk4bf_bits_in_byte[biti])); #else (dptr->d)[bytei] = (unsigned char)( ((dptr->d)[bytei]) & (~(dk4bf_bits_in_byte[biti])) ); #endif } back = 1; } else { dk4error_set_simple_error_code(erp, DK4_E_INVALID_ARGUMENTS); } } else { dk4error_set_simple_error_code(erp, DK4_E_INVALID_ARGUMENTS); } return back; } int dk4bf_get(int *dptr, dk4_bit_field_t const *bfptr, size_t bitno, dk4_er_t *erp) { size_t bytei; /* Byte index */ size_t biti; /* Bit index within byte */ int back = 0; #if DK4_USE_ASSERT assert(NULL != dptr); assert(NULL != bfptr); #endif if ((NULL != dptr) && (NULL != bfptr)) { if (bitno < bfptr->s) { bytei = bitno / 8; biti = bitno % 8; if (0x00 != (((bfptr->d)[bytei]) & (dk4bf_bits_in_byte[biti]))) { *dptr = 1; } else { *dptr = 0; } back = 1; } else { dk4error_set_simple_error_code(erp, DK4_E_INVALID_ARGUMENTS); } } else { dk4error_set_simple_error_code(erp, DK4_E_INVALID_ARGUMENTS); } return back; } void dk4bf_close(dk4_bit_field_t *ptr) { #if DK4_USE_ASSERT assert(NULL != ptr); #endif if (NULL != ptr) { dk4mem_release(ptr->d); dk4mem_free(ptr); } }