bitset.c 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* vim: tabstop=4 shiftwidth=4 noexpandtab
  2. * This file is part of ToaruOS and is released under the terms
  3. * of the NCSA / University of Illinois License - see LICENSE.md
  4. * Copyright (C) 2015 Dale Weiler
  5. * 2015 Kevin Lange
  6. */
  7. #include <kernel/bitset.h>
  8. #define CEIL(NUMBER, BASE) \
  9. (((NUMBER) + (BASE) - 1) & ~((BASE) - 1))
  10. #define iom \
  11. size_t index = bit >> 3; \
  12. bit = bit - index * 8; \
  13. size_t offset = bit & 7; \
  14. size_t mask = 1 << offset;
  15. void bitset_init(bitset_t *set, size_t size) {
  16. set->size = CEIL(size, 8);
  17. set->data = calloc(set->size, 1);
  18. }
  19. void bitset_free(bitset_t *set) {
  20. free(set->data);
  21. }
  22. static void bitset_resize(bitset_t *set, size_t size) {
  23. if (set->size >= size) {
  24. return;
  25. }
  26. set->data = realloc(set->data, size);
  27. memset(set->data + set->size, 0, size - set->size);
  28. set->size = size;
  29. }
  30. void bitset_set(bitset_t *set, size_t bit) {
  31. iom;
  32. if (set->size <= index) {
  33. bitset_resize(set, set->size << 1);
  34. }
  35. set->data[index] |= mask;
  36. }
  37. int bitset_ffub(bitset_t *set) {
  38. for (size_t i = 0; i < set->size * 8; i++) {
  39. if (bitset_test(set, i)) {
  40. continue;
  41. }
  42. return (int)i;
  43. }
  44. return -1;
  45. }
  46. void bitset_clear(bitset_t *set, size_t bit) {
  47. iom;
  48. set->data[index] &= ~mask;
  49. }
  50. int bitset_test(bitset_t *set, size_t bit) {
  51. iom;
  52. return !!(mask & set->data[index]);
  53. }