-
Notifications
You must be signed in to change notification settings - Fork 95
/
_bitarray.c
3353 lines (2837 loc) · 96.8 KB
/
_bitarray.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2008 - 2021, Ilan Schnell; All Rights Reserved
bitarray is published under the PSF license.
This file is the C part of the bitarray package.
All functionality of the bitarray object is implemented here.
Author: Ilan Schnell
*/
#define PY_SSIZE_T_CLEAN
#include "Python.h"
#include "pythoncapi_compat.h"
#include "bitarray.h"
/* size used when reading / writing blocks from files (in bytes) */
#define BLOCKSIZE 65536
#ifdef IS_PY3K
#define Py_TPFLAGS_HAVE_WEAKREFS 0
#define BYTES_SIZE_FMT "y#"
#else
#define BYTES_SIZE_FMT "s#"
#endif
#ifdef STDC_HEADERS
#include <stddef.h>
#else /* !STDC_HEADERS */
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h> /* For size_t */
#endif /* HAVE_SYS_TYPES_H */
#endif /* !STDC_HEADERS */
static int default_endian = ENDIAN_BIG;
static PyTypeObject Bitarray_Type;
#define bitarray_Check(obj) PyObject_TypeCheck((obj), &Bitarray_Type)
static int
resize(bitarrayobject *self, Py_ssize_t nbits)
{
const Py_ssize_t allocated = self->allocated, size = Py_SIZE(self);
Py_ssize_t newsize;
size_t new_allocated;
assert(allocated >= size && size == BYTES(self->nbits));
/* ob_item == NULL implies ob_size == allocated == 0 */
assert(self->ob_item != NULL || (size == 0 && allocated == 0));
/* allocated == 0 implies size == 0 */
assert(allocated != 0 || size == 0);
newsize = BYTES(nbits);
if (nbits < 0 || BITS(newsize) < 0) {
PyErr_Format(PyExc_OverflowError, "bitarray resize %zd", nbits);
return -1;
}
if (newsize == size) {
/* buffer size hasn't changed - bypass everything */
self->nbits = nbits;
return 0;
}
if (self->ob_exports > 0) {
PyErr_SetString(PyExc_BufferError,
"cannot resize bitarray that is exporting buffers");
return -1;
}
/* Bypass reallocation when a allocation is large enough to accommodate
the newsize. If the newsize falls lower than half the allocated size,
then proceed with the reallocation to shrink the bitarray.
*/
if (allocated >= newsize && newsize >= (allocated >> 1)) {
assert(self->ob_item != NULL || newsize == 0);
Py_SET_SIZE(self, newsize);
self->nbits = nbits;
return 0;
}
if (newsize == 0) {
PyMem_FREE(self->ob_item);
self->ob_item = NULL;
Py_SET_SIZE(self, 0);
self->allocated = 0;
self->nbits = 0;
return 0;
}
new_allocated = (size_t) newsize;
if (size == 0 && newsize <= 4)
/* When resizing an empty bitarray, we want at least 4 bytes. */
new_allocated = 4;
/* Over-allocate when the (previous) size is non-zero (as we often
extend an empty array on creation) and the size is actually
increasing. */
else if (size != 0 && newsize > size)
/* This over-allocates proportional to the bitarray size, making
room for additional growth.
The growth pattern is: 0, 4, 8, 16, 25, 34, 44, 54, 65, 77, ...
The pattern starts out the same as for lists but then
grows at a smaller rate so that larger bitarrays only overallocate
by about 1/16th -- this is done because bitarrays are assumed
to be memory critical. */
new_allocated += (newsize >> 4) + (newsize < 8 ? 3 : 7);
assert(new_allocated >= (size_t) newsize);
self->ob_item = PyMem_Realloc(self->ob_item, new_allocated);
if (self->ob_item == NULL) {
PyErr_NoMemory();
return -1;
}
Py_SET_SIZE(self, newsize);
self->allocated = new_allocated;
self->nbits = nbits;
return 0;
}
/* create new bitarray object without initialization of buffer */
static PyObject *
newbitarrayobject(PyTypeObject *type, Py_ssize_t nbits, int endian)
{
const Py_ssize_t nbytes = BYTES(nbits);
bitarrayobject *obj;
assert(nbits >= 0);
obj = (bitarrayobject *) type->tp_alloc(type, 0);
if (obj == NULL)
return NULL;
Py_SET_SIZE(obj, nbytes);
if (nbytes == 0) {
obj->ob_item = NULL;
}
else {
obj->ob_item = (char *) PyMem_Malloc((size_t) nbytes);
if (obj->ob_item == NULL) {
PyObject_Del(obj);
return PyErr_NoMemory();
}
}
obj->allocated = nbytes;
obj->nbits = nbits;
obj->endian = endian;
obj->ob_exports = 0;
obj->weakreflist = NULL;
return (PyObject *) obj;
}
static void
bitarray_dealloc(bitarrayobject *self)
{
if (self->weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) self);
if (self->ob_item != NULL)
PyMem_Free((void *) self->ob_item);
Py_TYPE(self)->tp_free((PyObject *) self);
}
/* reverse n bytes (starting at start) in buffer */
static void
bytereverse(bitarrayobject *self, Py_ssize_t start, Py_ssize_t n)
{
static char trans[256];
static int setup = 0;
Py_ssize_t i, stop = start + n;
assert(n >= 0);
assert(0 <= start && start <= Py_SIZE(self));
assert(0 <= stop && stop <= Py_SIZE(self));
if (!setup) {
/* setup translation table, which maps each byte to it's reversed:
trans = {0, 128, 64, 192, 32, 160, ..., 255} */
int j, k;
for (k = 0; k < 256; k++) {
trans[k] = 0x00;
for (j = 0; j < 8; j++)
if (1 << (7 - j) & k)
trans[k] |= 1 << j;
}
setup = 1;
}
setunused(self);
for (i = start; i < stop; i++)
self->ob_item[i] = trans[(unsigned char) self->ob_item[i]];
}
/* copy n bits from other (starting at b) onto self (starting at a) */
static void
copy_n(bitarrayobject *self, Py_ssize_t a,
bitarrayobject *other, Py_ssize_t b, Py_ssize_t n)
{
Py_ssize_t i;
assert(0 <= n && n <= self->nbits && n <= other->nbits);
assert(0 <= a && a <= self->nbits - n);
assert(0 <= b && b <= other->nbits - n);
if (n == 0)
return;
/* When the start positions are at byte positions, we can copy whole
bytes using memmove, and copy the remaining few bits individually.
Note that the order of these two operations matters when copying
self to self. */
if (a % 8 == 0 && b % 8 == 0 && n >= 8) {
const size_t bytes = n / 8;
const Py_ssize_t bits = BITS(bytes);
assert(bytes > 0 && bits <= n && n < bits + 8);
if (a > b)
copy_n(self, bits + a, other, bits + b, n - bits);
memmove(self->ob_item + a / 8, other->ob_item + b / 8, bytes);
if (self->endian != other->endian)
bytereverse(self, a / 8, bytes);
if (a <= b)
copy_n(self, bits + a, other, bits + b, n - bits);
return;
}
/* The two different types of looping are only relevant when copying
self to self, i.e. when copying a piece of an bitarrayobject onto
itself. */
if (a <= b) {
for (i = 0; i < n; i++) /* loop forward (delete) */
setbit(self, i + a, GETBIT(other, i + b));
}
else {
for (i = n - 1; i >= 0; i--) /* loop backwards (insert) */
setbit(self, i + a, GETBIT(other, i + b));
}
}
/* starting at start, delete n bits from self */
static int
delete_n(bitarrayobject *self, Py_ssize_t start, Py_ssize_t n)
{
assert(0 <= start && start <= self->nbits);
assert(0 <= n && n <= self->nbits - start);
copy_n(self, start, self, start + n, self->nbits - start - n);
return resize(self, self->nbits - n);
}
/* starting at start, insert n (uninitialized) bits into self */
static int
insert_n(bitarrayobject *self, Py_ssize_t start, Py_ssize_t n)
{
assert(0 <= start && start <= self->nbits);
assert(n >= 0);
if (resize(self, self->nbits + n) < 0)
return -1;
copy_n(self, start + n, self, start, self->nbits - start - n);
return 0;
}
static void
invert(bitarrayobject *self)
{
const Py_ssize_t nbytes = Py_SIZE(self);
Py_ssize_t i;
for (i = 0; i < nbytes; i++)
self->ob_item[i] = ~self->ob_item[i];
}
/* repeat self n times (negative n is treated as 0) */
static int
repeat(bitarrayobject *self, Py_ssize_t n)
{
const Py_ssize_t nbits = self->nbits;
Py_ssize_t i;
if (nbits == 0 || n == 1) /* nothing to do */
return 0;
if (n <= 0) /* clear */
return resize(self, 0);
assert(n > 1 && nbits > 0);
if (nbits > PY_SSIZE_T_MAX / n) {
PyErr_Format(PyExc_OverflowError,
"cannot repeat bitarray (of size %zd) %zd times",
nbits, n);
return -1;
}
if (resize(self, n * nbits) < 0)
return -1;
for (i = 1; i < n; i++)
copy_n(self, i * nbits, self, 0, nbits);
return 0;
}
/* set the bits from start to stop (excluding) in self to val */
static void
setrange(bitarrayobject *self, Py_ssize_t start, Py_ssize_t stop, int val)
{
Py_ssize_t i;
assert(0 <= start && start <= self->nbits);
assert(0 <= stop && stop <= self->nbits);
if (self->nbits == 0 || start >= stop)
return;
if (stop >= start + 8) {
const Py_ssize_t byte_start = BYTES(start);
const Py_ssize_t byte_stop = stop / 8;
for (i = start; i < BITS(byte_start); i++)
setbit(self, i, val);
memset(self->ob_item + byte_start, val ? 0xff : 0x00,
(size_t) (byte_stop - byte_start));
for (i = BITS(byte_stop); i < stop; i++)
setbit(self, i, val);
}
else {
for (i = start; i < stop; i++)
setbit(self, i, val);
}
}
/* Return number of 'vi' bits in range(start, stop).
This function never fails. */
static Py_ssize_t
count(bitarrayobject *self, int vi, Py_ssize_t start, Py_ssize_t stop)
{
Py_ssize_t res = 0, i;
assert(0 <= start && start <= self->nbits);
assert(0 <= stop && stop <= self->nbits);
assert(0 <= vi && vi <= 1);
assert(BYTES(stop) <= Py_SIZE(self));
if (self->nbits == 0 || start >= stop)
return 0;
if (stop >= start + 8) {
const Py_ssize_t byte_start = BYTES(start);
const Py_ssize_t byte_stop = stop / 8;
Py_ssize_t j;
for (i = start; i < BITS(byte_start); i++)
res += GETBIT(self, i);
for (j = byte_start; j < byte_stop; j++)
res += bitcount_lookup[(unsigned char) self->ob_item[j]];
for (i = BITS(byte_stop); i < stop; i++)
res += GETBIT(self, i);
}
else {
for (i = start; i < stop; i++)
res += GETBIT(self, i);
}
return vi ? res : stop - start - res;
}
/* Return index of first occurrence of vi, and -1 when vi is not found.
This function never fails. */
static Py_ssize_t
findfirst(bitarrayobject *self, int vi, Py_ssize_t start, Py_ssize_t stop)
{
Py_ssize_t i;
assert(0 <= start && start <= self->nbits);
assert(0 <= stop && stop <= self->nbits);
assert(0 <= vi && vi <= 1);
assert(BYTES(stop) <= Py_SIZE(self));
if (self->nbits == 0 || start >= stop)
return -1;
if (stop >= start + 8) {
/* seraching for 1 means: break when byte is not 0x00
searching for 0 means: break when byte is not 0xff */
const char c = vi ? 0x00 : 0xff;
/* skip ahead by checking whole bytes */
for (i = start / 8; i < BYTES(stop); i++) {
if (c ^ self->ob_item[i])
break;
}
if (start < BITS(i))
start = BITS(i);
}
/* fine grained search */
for (i = start; i < stop; i++) {
if (GETBIT(self, i) == vi)
return i;
}
return -1;
}
/* search for the first occurrence of bitarray xa (in self), starting at p,
and return its position (or -1 when not found)
*/
static Py_ssize_t
search(bitarrayobject *self, bitarrayobject *xa, Py_ssize_t p)
{
Py_ssize_t i;
assert(p >= 0);
if (xa->nbits == 1) /* faster for sparse bitarrays */
return findfirst(self, GETBIT(xa, 0), p, self->nbits);
while (p < self->nbits - xa->nbits + 1) {
for (i = 0; i < xa->nbits; i++)
if (GETBIT(self, p + i) != GETBIT(xa, i))
goto next;
return p;
next:
p++;
}
return -1;
}
static int
set_item(bitarrayobject *self, Py_ssize_t i, PyObject *v)
{
int vi;
assert(0 <= i && i < self->nbits);
if ((vi = pybit_as_int(v)) < 0)
return -1;
setbit(self, i, vi);
return 0;
}
static int
extend_bitarray(bitarrayobject *self, bitarrayobject *other)
{
/* We have to store the sizes before we resize, and since
other may be self, we also need to store other->nbits. */
const Py_ssize_t self_nbits = self->nbits;
const Py_ssize_t other_nbits = other->nbits;
if (resize(self, self_nbits + other_nbits) < 0)
return -1;
copy_n(self, self_nbits, other, 0, other_nbits);
return 0;
}
static int
extend_iter(bitarrayobject *self, PyObject *iter)
{
const Py_ssize_t original_nbits = self->nbits;
PyObject *item;
assert(PyIter_Check(iter));
while ((item = PyIter_Next(iter))) {
if (resize(self, self->nbits + 1) < 0)
goto error;
if (set_item(self, self->nbits - 1, item) < 0)
goto error;
Py_DECREF(item);
}
if (PyErr_Occurred())
return -1;
return 0;
error:
Py_DECREF(item);
resize(self, original_nbits);
return -1;
}
static int
extend_sequence(bitarrayobject *self, PyObject *sequence)
{
const Py_ssize_t original_nbits = self->nbits;
PyObject *item;
Py_ssize_t n, i;
assert(PySequence_Check(sequence));
n = PySequence_Size(sequence);
if (resize(self, self->nbits + n) < 0)
return -1;
for (i = 0; i < n; i++) {
item = PySequence_GetItem(sequence, i);
if (item == NULL || set_item(self, self->nbits - n + i, item) < 0) {
Py_XDECREF(item);
resize(self, original_nbits);
return -1;
}
Py_DECREF(item);
}
return 0;
}
static int
extend_bytes01(bitarrayobject *self, PyObject *bytes)
{
const Py_ssize_t original_nbits = self->nbits;
unsigned char c;
char *data;
int vi = 0; /* to avoid uninitialized warning for some compilers */
assert(PyBytes_Check(bytes));
data = PyBytes_AS_STRING(bytes);
while ((c = *data++)) {
switch (c) {
case '0': vi = 0; break;
case '1': vi = 1; break;
case ' ':
case '\n':
case '\r':
case '\t':
case '\v':
continue;
default:
PyErr_Format(PyExc_ValueError, "expected '0' or '1' "
"(or whitespace), got '%c' (0x%02x)", c, c);
resize(self, original_nbits); /* no bits added on error */
return -1;
}
if (resize(self, self->nbits + 1) < 0)
return -1;
setbit(self, self->nbits - 1, vi);
}
return 0;
}
static int
extend_unicode01(bitarrayobject *self, PyObject *unicode)
{
PyObject *bytes;
int res;
assert(PyUnicode_Check(unicode));
bytes = PyUnicode_AsASCIIString(unicode);
if (bytes == NULL)
return -1;
assert(PyBytes_Check(bytes));
res = extend_bytes01(self, bytes);
Py_DECREF(bytes); /* drop bytes */
return res;
}
static int
extend_dispatch(bitarrayobject *self, PyObject *obj)
{
PyObject *iter;
/* dispatch on type */
if (bitarray_Check(obj)) /* bitarray */
return extend_bitarray(self, (bitarrayobject *) obj);
if (PyBytes_Check(obj)) { /* bytes 01 */
#ifdef IS_PY3K
PyErr_SetString(PyExc_TypeError,
"cannot extend bitarray with 'bytes', "
"use .pack() or .frombytes() instead");
return -1;
#else
return extend_bytes01(self, obj);
#endif
}
if (PyUnicode_Check(obj)) /* unicode 01 */
return extend_unicode01(self, obj);
if (PySequence_Check(obj)) /* sequence */
return extend_sequence(self, obj);
if (PyIter_Check(obj)) /* iter */
return extend_iter(self, obj);
/* finally, try to get the iterator of the object */
iter = PyObject_GetIter(obj);
if (iter) {
int res;
res = extend_iter(self, iter);
Py_DECREF(iter);
return res;
}
PyErr_Format(PyExc_TypeError,
"'%s' object is not iterable", Py_TYPE(obj)->tp_name);
return -1;
}
static PyObject *
unpack(bitarrayobject *self, char zero, char one, const char *fmt)
{
PyObject *result;
Py_ssize_t i;
char *str;
str = (char *) PyMem_Malloc((size_t) self->nbits);
if (str == NULL)
return PyErr_NoMemory();
for (i = 0; i < self->nbits; i++)
str[i] = GETBIT(self, i) ? one : zero;
result = Py_BuildValue(fmt, str, self->nbits);
PyMem_Free((void *) str);
return result;
}
/* --------- helper functions not involving bitarrayobjects ------------ */
/* Normalize index (which may be negative), such that 0 <= i <= n */
static void
normalize_index(Py_ssize_t n, Py_ssize_t *i)
{
if (*i < 0) {
*i += n;
if (*i < 0)
*i = 0;
}
if (*i > n)
*i = n;
}
/**************************************************************************
Implementation of bitarray methods
**************************************************************************/
static PyObject *
bitarray_length(bitarrayobject *self)
{
PyErr_SetString(PyExc_NotImplementedError,
"self.length() has been deprecated since 1.5.1, "
"and was removed in 2.0.0. Use len(self) instead.");
return NULL;
}
static PyObject *
bitarray_copy(bitarrayobject *self)
{
PyObject *res;
res = newbitarrayobject(Py_TYPE(self), self->nbits, self->endian);
if (res == NULL)
return NULL;
memcpy(((bitarrayobject *) res)->ob_item, self->ob_item,
(size_t) Py_SIZE(self));
return res;
}
PyDoc_STRVAR(copy_doc,
"copy() -> bitarray\n\
\n\
Return a copy of the bitarray.");
static PyObject *
bitarray_count(bitarrayobject *self, PyObject *args)
{
PyObject *v = Py_True;
Py_ssize_t start = 0, stop = self->nbits;
int vi;
if (!PyArg_ParseTuple(args, "|Onn:count", &v, &start, &stop))
return NULL;
if ((vi = pybit_as_int(v)) < 0)
return NULL;
normalize_index(self->nbits, &start);
normalize_index(self->nbits, &stop);
return PyLong_FromSsize_t(count(self, vi, start, stop));
}
PyDoc_STRVAR(count_doc,
"count(value=1, start=0, stop=<end of array>, /) -> int\n\
\n\
Count the number of occurrences of `value` in the bitarray.");
static PyObject *
bitarray_index(bitarrayobject *self, PyObject *args)
{
Py_ssize_t start = 0, stop = self->nbits, i;
PyObject *value;
int vi;
if (!PyArg_ParseTuple(args, "O|nn:index", &value, &start, &stop))
return NULL;
if ((vi = pybit_as_int(value)) < 0)
return NULL;
normalize_index(self->nbits, &start);
normalize_index(self->nbits, &stop);
if ((i = findfirst(self, vi, start, stop)) < 0)
return PyErr_Format(PyExc_ValueError, "%d is not in bitarray", vi);
return PyLong_FromSsize_t(i);
}
PyDoc_STRVAR(index_doc,
"index(value, start=0, stop=<end of array>, /) -> int\n\
\n\
Return index of the first occurrence of `value` in the bitarray.\n\
Raises `ValueError` if the value is not present.");
static PyObject *
bitarray_extend(bitarrayobject *self, PyObject *obj)
{
if (extend_dispatch(self, obj) < 0)
return NULL;
Py_RETURN_NONE;
}
PyDoc_STRVAR(extend_doc,
"extend(iterable, /)\n\
\n\
Append all the items from `iterable` to the end of the bitarray.\n\
If the iterable is a string, each `0` and `1` are appended as\n\
bits (ignoring whitespace).");
static PyObject *
bitarray_search(bitarrayobject *self, PyObject *args)
{
PyObject *list = NULL; /* list of matching positions to be returned */
PyObject *item = NULL, *x;
Py_ssize_t limit = -1;
bitarrayobject *xa;
Py_ssize_t p = 0;
if (!PyArg_ParseTuple(args, "O|n:search", &x, &limit))
return NULL;
if (!bitarray_Check(x)) {
PyErr_SetString(PyExc_TypeError, "bitarray expected for search");
return NULL;
}
xa = (bitarrayobject *) x;
if (xa->nbits == 0) {
PyErr_SetString(PyExc_ValueError, "can't search for empty bitarray");
return NULL;
}
list = PyList_New(0);
if (list == NULL)
return NULL;
if (xa->nbits > self->nbits || limit == 0)
return list;
while ((p = search(self, xa, p)) >= 0) {
item = PyLong_FromSsize_t(p++);
if (item == NULL || PyList_Append(list, item) < 0) {
Py_XDECREF(item);
Py_XDECREF(list);
return NULL;
}
Py_DECREF(item);
if (limit > 0 && PyList_Size(list) >= limit)
break;
}
return list;
}
PyDoc_STRVAR(search_doc,
"search(bitarray, limit=<none>, /) -> list\n\
\n\
Searches for the given bitarray in self, and return the list of start\n\
positions.\n\
The optional argument limits the number of search results to the integer\n\
specified. By default, all search results are returned.");
static PyObject *
bitarray_buffer_info(bitarrayobject *self)
{
PyObject *res, *ptr;
ptr = PyLong_FromVoidPtr(self->ob_item),
res = Py_BuildValue("Onsin",
ptr,
Py_SIZE(self),
ENDIAN_STR(self),
(int) (BITS(Py_SIZE(self)) - self->nbits),
self->allocated);
Py_DECREF(ptr);
return res;
}
PyDoc_STRVAR(buffer_info_doc,
"buffer_info() -> tuple\n\
\n\
Return a tuple (address, size, endianness, unused, allocated) giving the\n\
memory address of the bitarray's buffer, the buffer size (in bytes),\n\
the bit endianness as a string, the number of unused bits within the last\n\
byte, and the allocated memory for the buffer (in bytes).");
static PyObject *
bitarray_endian(bitarrayobject *self)
{
return Py_BuildValue("s", ENDIAN_STR(self));
}
PyDoc_STRVAR(endian_doc,
"endian() -> str\n\
\n\
Return the bit endianness of the bitarray as a string (`little` or `big`).");
static PyObject *
bitarray_append(bitarrayobject *self, PyObject *value)
{
int vi;
if ((vi = pybit_as_int(value)) < 0)
return NULL;
if (resize(self, self->nbits + 1) < 0)
return NULL;
setbit(self, self->nbits - 1, vi);
Py_RETURN_NONE;
}
PyDoc_STRVAR(append_doc,
"append(item, /)\n\
\n\
Append `item` to the end of the bitarray.");
static PyObject *
bitarray_all(bitarrayobject *self)
{
return PyBool_FromLong(findfirst(self, 0, 0, self->nbits) == -1);
}
PyDoc_STRVAR(all_doc,
"all() -> bool\n\
\n\
Return True when all bits in the array are True.\n\
Note that `a.all()` is faster than `all(a)`.");
static PyObject *
bitarray_any(bitarrayobject *self)
{
return PyBool_FromLong(findfirst(self, 1, 0, self->nbits) >= 0);
}
PyDoc_STRVAR(any_doc,
"any() -> bool\n\
\n\
Return True when any bit in the array is True.\n\
Note that `a.any()` is faster than `any(a)`.");
static PyObject *
bitarray_reduce(bitarrayobject *self)
{
const Py_ssize_t nbytes = Py_SIZE(self);
PyObject *dict, *repr = NULL, *result = NULL;
char *data;
dict = PyObject_GetAttrString((PyObject *) self, "__dict__");
if (dict == NULL) {
PyErr_Clear();
dict = Py_None;
Py_INCREF(dict);
}
data = (char *) PyMem_Malloc(nbytes + 1);
if (data == NULL) {
PyErr_NoMemory();
goto error;
}
/* first byte contains the number of unused bits */
*data = (char) setunused(self);
/* remaining bytes contain buffer */
memcpy(data + 1, self->ob_item, (size_t) nbytes);
repr = PyBytes_FromStringAndSize(data, nbytes + 1);
if (repr == NULL)
goto error;
PyMem_Free((void *) data);
result = Py_BuildValue("O(Os)O", Py_TYPE(self),
repr, ENDIAN_STR(self), dict);
error:
Py_DECREF(dict);
Py_XDECREF(repr);
return result;
}
PyDoc_STRVAR(reduce_doc, "state information for pickling");
/* The head byte % 8 specifies the number of unused bits (in last buffer
byte), the remaining bytes consist of the buffer itself */
static PyObject *
unpickle(PyTypeObject *type, PyObject *bytes, int endian)
{
PyObject *res;
Py_ssize_t nbytes;
unsigned char head;
char *data;
assert(PyBytes_Check(bytes));
nbytes = PyBytes_GET_SIZE(bytes);
assert(nbytes > 0);
data = PyBytes_AS_STRING(bytes);
head = *data;
if (nbytes == 1 && head % 8)
return PyErr_Format(PyExc_ValueError,
"invalid header byte 0x%02x", head);
res = newbitarrayobject(type,
BITS(nbytes - 1) - ((Py_ssize_t) (head % 8)),
endian);
if (res == NULL)
return NULL;
memcpy(((bitarrayobject *) res)->ob_item, data + 1, (size_t) nbytes - 1);
return res;
}
static PyObject *
bitarray_reverse(bitarrayobject *self)
{
const Py_ssize_t m = self->nbits - 1; /* index of last item */
PyObject *t; /* temp bitarray to store lower half of self */
Py_ssize_t i;
if (self->nbits < 2) /* nothing needs to be done */
Py_RETURN_NONE;
t = newbitarrayobject(Py_TYPE(self), self->nbits / 2, self->endian);
if (t == NULL)
return NULL;
#define tt ((bitarrayobject *) t)
/* copy lower half of array into temporary array */
memcpy(tt->ob_item, self->ob_item, (size_t) Py_SIZE(tt));
/* reverse upper half onto the lower half. */
for (i = 0; i < tt->nbits; i++)
setbit(self, i, GETBIT(self, m - i));
/* reverse the stored away lower half onto the upper half of self. */
for (i = 0; i < tt->nbits; i++)
setbit(self, m - i, GETBIT(tt, i));
#undef tt
Py_DECREF(t);
Py_RETURN_NONE;
}
PyDoc_STRVAR(reverse_doc,
"reverse()\n\
\n\
Reverse the order of bits in the array (in-place).");
static PyObject *
bitarray_fill(bitarrayobject *self)
{
long p;
p = setunused(self);
self->nbits += p;
return PyLong_FromLong(p);
}
PyDoc_STRVAR(fill_doc,
"fill() -> int\n\
\n\
Add zeros to the end of the bitarray, such that the length of the bitarray\n\
will be a multiple of 8, and return the number of bits added (0..7).");
static PyObject *
bitarray_invert(bitarrayobject *self, PyObject *args)
{
Py_ssize_t i = PY_SSIZE_T_MAX;
if (!PyArg_ParseTuple(args, "|n:invert", &i))
return NULL;
if (i == PY_SSIZE_T_MAX) { /* default - invert all bits */