blob: f5bfd41bd653b2ae0bcc6f882f180a968a5689aa [file] [log] [blame]
Guido van Rossumf70e43a1991-02-19 12:39:46 +00001
Guido van Rossum3f5da241990-12-20 15:06:42 +00002/* Bitset primitives used by the parser generator */
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00003
Guido van Rossum3f5da241990-12-20 15:06:42 +00004#include "pgenheaders.h"
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00005#include "bitset.h"
6
7bitset
Thomas Wouters23c9e002000-07-22 19:20:54 +00008newbitset(int nbits)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +00009{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000010 int nbytes = NBYTES(nbits);
11 bitset ss = (char *)PyObject_MALLOC(sizeof(BYTE) * nbytes);
12
13 if (ss == NULL)
14 Py_FatalError("no mem for bitset");
15
16 ss += nbytes;
17 while (--nbytes >= 0)
18 *--ss = 0;
19 return ss;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000020}
21
22void
Thomas Wouters23c9e002000-07-22 19:20:54 +000023delbitset(bitset ss)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000024{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000025 PyObject_FREE(ss);
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000026}
27
28int
Thomas Wouters23c9e002000-07-22 19:20:54 +000029addbit(bitset ss, int ibit)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000030{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000031 int ibyte = BIT2BYTE(ibit);
32 BYTE mask = BIT2MASK(ibit);
33
34 if (ss[ibyte] & mask)
35 return 0; /* Bit already set */
36 ss[ibyte] |= mask;
37 return 1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000038}
39
40#if 0 /* Now a macro */
41int
Thomas Wouters23c9e002000-07-22 19:20:54 +000042testbit(bitset ss, int ibit)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000043{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 return (ss[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000045}
46#endif
47
48int
Thomas Wouters23c9e002000-07-22 19:20:54 +000049samebitset(bitset ss1, bitset ss2, int nbits)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 int i;
52
53 for (i = NBYTES(nbits); --i >= 0; )
54 if (*ss1++ != *ss2++)
55 return 0;
56 return 1;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000057}
58
59void
Thomas Wouters23c9e002000-07-22 19:20:54 +000060mergebitset(bitset ss1, bitset ss2, int nbits)
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000061{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000062 int i;
63
64 for (i = NBYTES(nbits); --i >= 0; )
65 *ss1++ |= *ss2++;
Guido van Rossum85a5fbb1990-10-14 12:07:46 +000066}