home *** CD-ROM | disk | FTP | other *** search
- /**********************************************************************
- *
- * bitset.c
- *
- * copyright (c) 1988 j. alan eldridge
- *
- * this code will run correctly on machines where an int
- * is either a short or a long (i.e., 2 or 4 bytes)
- *
- *********************************************************************/
-
-
- #include <stdlib.h>
- #include <limits.h>
-
- #include <bitset.h>
-
-
- #define INT_BITS (CHAR_BIT * sizeof(int))
-
- #define BITMAP_SIZE(lo,hi) (((hi)-(lo))/INT_BITS + 1)
-
- int
- bitset_new(bsp, lo, hi)
- BITSET *bsp;
- int lo;
- int hi;
- {
- bsp->bitmap = calloc(BITMAP_SIZE(lo,hi), sizeof(int));
-
- if (bsp->bitmap) {
- bsp->lo = lo;
- bsp->hi = hi;
- bsp->n_memb = 0;
- return 0;
- } else
- return -1;
- }
-
- int
- bitset_clr(bsp)
- BITSET *bsp;
- {
- if (bsp->bitmap) {
- bsp->n_memb = 0;
- memset(bsp->bitmap, 0, BITMAP_SIZE(bsp->lo,bsp->hi) * sizeof(int));
- return 0;
- } else
- return -1;
- }
-
- int
- bitset_set(bsp)
- BITSET *bsp;
- {
- if (bsp->bitmap) {
- bsp->n_memb = bsp->hi - bsp->lo + 1;
- memset(bsp->bitmap, 0xff, BITMAP_SIZE(bsp->lo,bsp->hi) * sizeof(int));
- return 0;
- } else
- return -1;
- }
-
- int
- bitset_free(bsp)
- BITSET *bsp;
- {
- if (bsp->bitmap) {
- free(bsp->bitmap);
- bsp->bitmap = NULL;
- bsp->lo =
- bsp->hi =
- bsp->n_memb = 0;
- }
- return 0;
- }
-
- int
- bitset_cnt(bsp)
- BITSET *bsp;
- {
- return bsp->n_memb;
- }
-
- static long bitmasks[] = {
- 0x00000001, 0x00000002, 0x00000004, 0x00000008,
- 0x00000010, 0x00000020, 0x00000040, 0x00000080,
- 0x00000100, 0x00000200, 0x00000400, 0x00000800,
- 0x00001000, 0x00002000, 0x00004000, 0x00008000,
- 0x00010000, 0x00020000, 0x00040000, 0x00080000,
- 0x00100000, 0x00200000, 0x00400000, 0x00800000,
- 0x01000000, 0x02000000, 0x04000000, 0x08000000,
- 0x10000000, 0x20000000, 0x40000000, 0x80000000
- };
-
- static int
- locate_bit(bsp, val, mask_p)
- BITSET *bsp;
- int val;
- int *mask_p;
- {
- int abs_val, byte;
-
- abs_val = val - bsp->lo;
-
- *mask_p = bitmasks[abs_val % INT_BITS];
- return abs_val / INT_BITS;
- }
-
- int
- bitset_in(bsp, val)
- BITSET *bsp;
- int val;
- {
- int mask, byte;
-
- if (val < bsp->lo || val > bsp->hi)
- return -1;
-
- byte = locate_bit(bsp, val, &mask);
-
- return (bsp->bitmap[byte] & mask) != 0;
- }
-
- int
- bitset_add(bsp, val)
- BITSET *bsp;
- int val;
- {
- int mask, byte, found;
-
- found = bitset_in(bsp, val);
-
- if (found >= 0) {
- if (!found) {
- byte = locate_bit(bsp, val, &mask);
- bsp->bitmap[byte] |= mask;
- bsp->n_memb++;
- }
- return 0;
- } else
- return -1;
- }
-
- int
- bitset_rmv(bsp, val)
- BITSET *bsp;
- int val;
- {
- int mask, byte, found;
-
- found = bitset_in(bsp, val);
-
- if (found == 1) {
- byte = locate_bit(bsp, val, &mask);
- bsp->bitmap[byte] &= ~mask;
- bsp->n_memb--;
- }
-
- return found;
- }
-
-