-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathteds_bitvector.c
1682 lines (1460 loc) · 55.1 KB
/
teds_bitvector.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
/*
+----------------------------------------------------------------------+
| teds extension for PHP |
| See COPYING file for further copyright information |
+----------------------------------------------------------------------+
| Author: Tyson Andre <[email protected]> |
+----------------------------------------------------------------------+
*/
/* This is based on spl_fixedarray.c but has lower overhead (when count(bit_size) is known) and is more efficient to push and remove elements from the end of the list */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "zend_exceptions.h"
#include "php_teds.h"
#include "teds.h"
#include "teds_bitvector_arginfo.h"
#include "teds_bitvector.h"
#include "teds_interfaces.h"
#include "teds_exceptions.h"
// #include "ext/spl/spl_functions.h"
#include "ext/spl/spl_exceptions.h"
#include "ext/spl/spl_iterators.h"
#include "ext/json/php_json.h"
#include "teds_util.h"
#include "teds_serialize_util.h"
#include <stdbool.h>
#define BYTE_OF_BIT_POSITION(n) ((n) >> 3)
#define BYTES_FOR_BIT_SIZE(n) BYTE_OF_BIT_POSITION((n) + 7)
/* zend_alloc.c allocations are at least 8 bytes. */
#define TEDS_MIN_BITVECTOR_BITS (8 * 8)
/* Avoid overflow */
#if SIZEOF_ZEND_LONG > SIZEOF_SIZE_T
#error expected SIZEOF_ZEND_LONG <= SIZEOF_SIZE_T
#endif
/* Returns a positive integer that is a multiple of TEDS_MIN_BITVECTOR_BITS */
static size_t teds_bitvector_compute_next_valid_capacity(size_t size) {
return (size + TEDS_MIN_BITVECTOR_BITS) & ~(TEDS_MIN_BITVECTOR_BITS - 1);
}
/* Low enough to check for overflow */
#define TEDS_MAX_BITVECTOR_BITS (((size_t) 1) << (SIZEOF_ZEND_LONG * 8 - 2))
static zend_always_inline bool teds_bitvector_is_bool(const zval *offset) {
//return ((uint8_t)(Z_TYPE_P(offset) - IS_FALSE)) <= 1;
return EXPECTED(Z_TYPE_P(offset) == IS_FALSE || Z_TYPE_P(offset) == IS_TRUE);
}
#define TEDS_BITVECTOR_VALUE_TO_BOOL_OR_THROW(value, value_zv) do { \
const zval *_tmp = (value_zv); \
if (UNEXPECTED(!teds_bitvector_is_bool(_tmp))) { \
if (EXPECTED(Z_TYPE_P(_tmp) == IS_REFERENCE)) { \
_tmp = Z_REFVAL_P(_tmp); \
if (EXPECTED(teds_bitvector_is_bool(_tmp))) { \
(value) = Z_TYPE_P(_tmp) != IS_FALSE; \
break; \
} \
} \
zend_type_error("Illegal Teds\\BitVector value type %s", zend_zval_type_name(_tmp)); \
return; \
} else { \
(value) = Z_TYPE_P(_tmp) != IS_FALSE; \
} \
} while (0)
/* Though rare, it is possible to have 64-bit zend_longs and a 32-bit size_t. */
#define MAX_ZVAL_COUNT ((SIZE_MAX / sizeof(zval)) - 1)
#define MAX_VALID_OFFSET ((size_t)(MAX_ZVAL_COUNT > ZEND_LONG_MAX ? ZEND_LONG_MAX : MAX_ZVAL_COUNT))
zend_object_handlers teds_handler_BitVector;
zend_class_entry *teds_ce_BitVector;
typedef struct _teds_bitvector_entries {
uint8_t *entries_bits;
/* This is deliberately a size_t instead of an uint32_t.
* This is memory efficient enough that it's more likely to be used in practice for more than 4 billion values,
* and garbage collection isn't a problem.
* The memory usage in bytes is 1/8th of the bit_capacity (BYTE_OF_BIT_POSITION(bit_capacity)). */
size_t bit_size;
size_t bit_capacity;
teds_intrusive_dllist active_iterators;
} teds_bitvector_entries;
typedef struct _teds_bitvector {
teds_bitvector_entries array;
zend_object std;
} teds_bitvector;
/* Used by InternalIterator returned by BitVector->getIterator() */
typedef struct _teds_bitvector_it {
zend_object_iterator intern;
size_t current;
/* Temporary memory location to store the most recent get_current_value() result */
zval tmp;
teds_intrusive_dllist_node dllist_node;
} teds_bitvector_it;
static void teds_bitvector_entries_raise_capacity(teds_bitvector_entries *intern, const size_t new_capacity);
static zend_always_inline void teds_bitvector_entries_push(teds_bitvector_entries *array, const bool value, const bool check_capacity);
static zend_always_inline void teds_bitvector_entries_copy_offset(const teds_bitvector_entries *array, const size_t offset, zval *dst, bool pop);
static zend_always_inline zval *teds_bitvector_entries_read_offset(const teds_bitvector_entries *intern, const size_t offset, zval *tmp);
static void teds_bitvector_entries_init_from_array_values(teds_bitvector_entries *array, zend_array *raw_data);
static zend_array *teds_bitvector_entries_to_refcounted_array(const teds_bitvector_entries *array);
/*
* If a bit_size this large is encountered, assume the allocation will likely fail or
* future changes to the bit_capacity will overflow.
*/
static ZEND_COLD void teds_error_noreturn_max_bitvector_capacity()
{
zend_error_noreturn(E_ERROR, "exceeded max valid Teds\\BitVector bit_capacity");
}
static zend_always_inline teds_bitvector *teds_bitvector_from_object(zend_object *obj)
{
return (teds_bitvector*)((char*)(obj) - XtOffsetOf(teds_bitvector, std));
}
static zend_always_inline zend_object *teds_bitvector_to_object(teds_bitvector_entries *array)
{
return (zend_object*)((char*)(array) + XtOffsetOf(teds_bitvector, std));
}
static zend_always_inline teds_bitvector_it *teds_bitvector_it_from_node(teds_intrusive_dllist_node *node)
{
return (teds_bitvector_it*)((char*)(node) - XtOffsetOf(teds_bitvector_it, dllist_node));
}
#define Z_BITVECTOR_P(zv) (teds_bitvector_from_object(Z_OBJ_P((zv))))
#define Z_BITVECTOR_ENTRIES_P(zv) (&(Z_BITVECTOR_P((zv))->array))
static zend_always_inline bool teds_bitvector_entries_empty_capacity(const teds_bitvector_entries *array)
{
if (array->bit_capacity > 0) {
ZEND_ASSERT(array->entries_bits != (void *)empty_entry_list);
return false;
}
// This bitvector may have reserved bit_capacity.
return true;
}
static zend_always_inline bool teds_bitvector_entries_uninitialized(const teds_bitvector_entries *array)
{
if (array->entries_bits == NULL) {
ZEND_ASSERT(array->bit_size == 0);
ZEND_ASSERT(array->bit_capacity == 0);
return true;
}
ZEND_ASSERT((array->entries_bits == (void *)empty_entry_list && array->bit_capacity == 0) || array->bit_capacity > 0);
return false;
}
static void teds_bitvector_entries_raise_capacity(teds_bitvector_entries *array, const size_t new_capacity) {
ZEND_ASSERT((array->bit_capacity & 7) == 0);
ZEND_ASSERT((new_capacity & (TEDS_MIN_BITVECTOR_BITS - 1)) == 0);
ZEND_ASSERT(new_capacity > array->bit_capacity);
const size_t bytes_needed = BYTES_FOR_BIT_SIZE(new_capacity);
if (UNEXPECTED(new_capacity >= TEDS_MAX_BITVECTOR_BITS)) {
teds_error_noreturn_max_bitvector_capacity();
return;
}
//fprintf(stderr, "reallocate %d bytes %d bits\n", (int)bytes_needed, (int)new_capacity);
if (array->bit_capacity == 0) {
array->entries_bits = emalloc(bytes_needed);
} else {
array->entries_bits = erealloc(array->entries_bits, bytes_needed);
}
array->bit_capacity = new_capacity;
ZEND_ASSERT(array->entries_bits != NULL);
}
static inline void teds_bitvector_entries_shrink_capacity(teds_bitvector_entries *array, const size_t bit_size, const size_t bit_capacity, void *old_entries_bits) {
ZEND_ASSERT(bit_size <= bit_capacity);
ZEND_ASSERT(bit_size == array->bit_size);
ZEND_ASSERT(bit_capacity > 0);
ZEND_ASSERT(bit_capacity < array->bit_capacity);
ZEND_ASSERT(old_entries_bits == array->entries_bits);
ZEND_ASSERT((bit_capacity & 7) == 0);
array->bit_capacity = bit_capacity;
array->entries_bits = erealloc2(old_entries_bits, bit_capacity >> 3, BYTES_FOR_BIT_SIZE(bit_size));
ZEND_ASSERT(array->entries_bits != NULL);
}
static zend_always_inline void teds_bitvector_entries_set_empty_list(teds_bitvector_entries *array) {
array->bit_size = 0;
array->bit_capacity = 0;
array->entries_bits = (void *)empty_entry_list;
}
static void teds_bitvector_entries_init_from_traversable(teds_bitvector_entries *array, zend_object *obj)
{
zend_class_entry *ce = obj->ce;
zend_object_iterator *iter;
teds_bitvector_entries_set_empty_list(array);
zval tmp_obj;
ZVAL_OBJ(&tmp_obj, obj);
iter = ce->get_iterator(ce, &tmp_obj, 0);
if (UNEXPECTED(EG(exception))) {
return;
}
const zend_object_iterator_funcs *funcs = iter->funcs;
if (funcs->rewind) {
funcs->rewind(iter);
if (UNEXPECTED(EG(exception))) {
goto cleanup_iter;
}
}
/* Reindex keys from 0. */
while (funcs->valid(iter) == SUCCESS) {
if (UNEXPECTED(EG(exception))) {
break;
}
zval *value_zv = funcs->get_current_data(iter);
if (UNEXPECTED(EG(exception))) {
break;
}
bool value;
if (UNEXPECTED(!teds_bitvector_is_bool(value_zv))) {
if (EXPECTED(Z_TYPE_P(value_zv) == IS_REFERENCE)) {
value_zv = Z_REFVAL_P(value_zv);
if (UNEXPECTED(!teds_bitvector_is_bool(value_zv))) {
goto not_a_bool;
}
value = Z_TYPE_P(value_zv) != IS_FALSE;
} else {
not_a_bool:
zend_type_error("Illegal Teds\\BitVector value type %s", zend_zval_type_name(value_zv));
break;
}
} else {
value = Z_TYPE_P(value_zv) != IS_FALSE;
}
teds_bitvector_entries_push(array, value, true);
iter->index++;
funcs->move_forward(iter);
if (UNEXPECTED(EG(exception))) {
break;
}
}
cleanup_iter:
if (iter) {
zend_iterator_dtor(iter);
}
}
static void teds_bitvector_entries_copy_ctor(teds_bitvector_entries *to, const teds_bitvector_entries *from)
{
zend_long bit_size = from->bit_size;
if (!bit_size) {
teds_bitvector_entries_set_empty_list(to);
return;
}
to->bit_size = 0; /* reset bit_size in case emalloc() fails */
to->bit_capacity = 0;
const size_t bytes_needed = BYTES_FOR_BIT_SIZE(bit_size);
to->entries_bits = safe_emalloc(bit_size, bytes_needed, 0);
to->bit_size = bit_size;
to->bit_capacity = bytes_needed * 8;
memcpy(to->entries_bits, from->entries_bits, BYTES_FOR_BIT_SIZE(bit_size));
}
static HashTable* teds_bitvector_get_properties_for(zend_object *obj, zend_prop_purpose purpose)
{
(void)purpose;
teds_bitvector_entries *array = &teds_bitvector_from_object(obj)->array;
if (!array->bit_size) {
/* debug_zval_dump DEBUG purpose requires null or a refcounted array. */
return NULL;
}
/* var_export uses get_properties_for for infinite recursion detection rather than get_properties(Z_OBJPROP).
* or checking for recursion on the object itself (php_var_dump).
* However, BitVector can only contain booleans, making infinite recursion impossible, so it's safe to return new arrays. */
return teds_bitvector_entries_to_refcounted_array(array);
}
static void teds_bitvector_free_storage(zend_object *object)
{
teds_bitvector *intern = teds_bitvector_from_object(object);
if (!teds_bitvector_entries_empty_capacity(&intern->array)) {
efree(intern->array.entries_bits);
}
zend_object_std_dtor(object);
}
static zend_object *teds_bitvector_new_ex(zend_class_entry *class_type, zend_object *orig, bool clone_orig)
{
teds_bitvector *intern = zend_object_alloc(sizeof(teds_bitvector), class_type);
/* This is a final class */
ZEND_ASSERT(class_type == teds_ce_BitVector);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &teds_handler_BitVector;
if (orig && clone_orig) {
teds_bitvector *other = teds_bitvector_from_object(orig);
teds_bitvector_entries_copy_ctor(&intern->array, &other->array);
} else {
intern->array.entries_bits = NULL;
}
return &intern->std;
}
static zend_object *teds_bitvector_new(zend_class_entry *class_type)
{
return teds_bitvector_new_ex(class_type, NULL, 0);
}
static zend_object *teds_bitvector_clone(zend_object *old_object)
{
zend_object *new_object = teds_bitvector_new_ex(old_object->ce, old_object, 1);
teds_assert_object_has_empty_member_list(new_object);
return new_object;
}
static TEDS_COUNT_ELEMENTS_RETURN_TYPE teds_bitvector_count_elements(zend_object *object, zend_long *count)
{
const teds_bitvector *intern = teds_bitvector_from_object(object);
*count = intern->array.bit_size;
return SUCCESS;
}
/* Get number of entries in this bitvector */
PHP_METHOD(Teds_BitVector, count)
{
ZEND_PARSE_PARAMETERS_NONE();
RETURN_LONG(Z_BITVECTOR_ENTRIES_P(ZEND_THIS)->bit_size);
}
/* Get number of entries in this bitvector */
PHP_METHOD(Teds_BitVector, capacity)
{
ZEND_PARSE_PARAMETERS_NONE();
RETURN_LONG(Z_BITVECTOR_ENTRIES_P(ZEND_THIS)->bit_capacity);
}
/* Check if the bitvector is empty. */
PHP_METHOD(Teds_BitVector, isEmpty)
{
ZEND_PARSE_PARAMETERS_NONE();
RETURN_BOOL(Z_BITVECTOR_ENTRIES_P(ZEND_THIS)->bit_size == 0);
}
static void teds_bitvector_set_range(teds_bitvector_entries *const array, const size_t start_bit, const size_t end_bit, const bool value_bool) {
ZEND_ASSERT(start_bit < end_bit);
ZEND_ASSERT(end_bit < array->bit_capacity);
uint8_t *const entries_bits = array->entries_bits;
ZEND_ASSERT(entries_bits != NULL);
const int8_t value = value_bool ? -1 : 0;
const size_t start_byte_offset = (start_bit + 7) >> 3;
const size_t end_byte_offset = (end_bit + 7) >> 3;
const uint8_t start_mask = (1 << (start_bit & 7)) - 1;
// fprintf(stderr, "start_bit=%d end_bit=%d start_byte_offset=%d end_byte_offset=%d value=%d start_mask=%d\n", (int)start_bit, (int)end_bit, (int)start_byte_offset, (int)end_byte_offset, (int)value, (int)start_mask);
if (start_bit & 7) {
/* Set/clear upper bits */
if (value) {
entries_bits[start_bit >> 3] |= 0xff ^ start_mask;
} else {
entries_bits[start_bit >> 3] &= start_mask;
}
}
if (start_byte_offset < end_byte_offset) {
memset(&entries_bits[start_byte_offset], value_bool ? -1 : 0, end_byte_offset - start_byte_offset);
}
}
/* Set size in bits of this BitVector */
PHP_METHOD(Teds_BitVector, setSize)
{
zend_long size_signed;
bool default_bool = false;
ZEND_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_LONG(size_signed)
Z_PARAM_OPTIONAL
Z_PARAM_BOOL(default_bool)
ZEND_PARSE_PARAMETERS_END();
if (UNEXPECTED(size_signed < 0)) {
zend_argument_value_error(1, "must be greater than or equal to 0");
RETURN_THROWS();
}
const zend_ulong size = size_signed;
teds_bitvector_entries *const array = Z_BITVECTOR_ENTRIES_P(ZEND_THIS);
const size_t old_size = array->bit_size;
if (size <= old_size) {
array->bit_size = size;
const size_t capacity = teds_bitvector_compute_next_valid_capacity(size);
if (UNEXPECTED(capacity < array->bit_capacity)) {
teds_bitvector_entries_shrink_capacity(array, size, capacity, array->entries_bits);
}
TEDS_RETURN_VOID();
}
/* Raise the capacity as needed and fill the space with nulls */
if (UNEXPECTED(size > array->bit_capacity)) {
teds_bitvector_entries_raise_capacity(array, teds_bitvector_compute_next_valid_capacity(size + (size >> 2)));
}
teds_bitvector_set_range(array, old_size, size, default_bool);
array->bit_size = size;
TEDS_RETURN_VOID();
}
/* Create this from an optional iterable */
PHP_METHOD(Teds_BitVector, __construct)
{
zval *object = ZEND_THIS;
zval* iterable = NULL;
ZEND_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_ITERABLE(iterable)
ZEND_PARSE_PARAMETERS_END();
teds_bitvector_entries *array = Z_BITVECTOR_ENTRIES_P(object);
if (UNEXPECTED(!teds_bitvector_entries_uninitialized(array))) {
zend_throw_exception(spl_ce_RuntimeException, "Called Teds\\BitVector::__construct twice", 0);
RETURN_THROWS();
}
if (!iterable) {
teds_bitvector_entries_set_empty_list(array);
return;
}
switch (Z_TYPE_P(iterable)) {
case IS_ARRAY:
teds_bitvector_entries_init_from_array_values(array, Z_ARRVAL_P(iterable));
return;
case IS_OBJECT:
teds_bitvector_entries_init_from_traversable(array, Z_OBJ_P(iterable));
return;
EMPTY_SWITCH_DEFAULT_CASE();
}
}
PHP_METHOD(Teds_BitVector, clear)
{
ZEND_PARSE_PARAMETERS_NONE();
teds_bitvector_entries *array = Z_BITVECTOR_ENTRIES_P(ZEND_THIS);
if (!teds_bitvector_entries_empty_capacity(array)) {
efree(array->entries_bits);
}
teds_bitvector_entries_set_empty_list(array);
TEDS_RETURN_VOID();
}
PHP_METHOD(Teds_BitVector, getIterator)
{
ZEND_PARSE_PARAMETERS_NONE();
zend_create_internal_iterator_zval(return_value, ZEND_THIS);
}
static void teds_bitvector_it_dtor(zend_object_iterator *iter)
{
teds_intrusive_dllist_node *node = &((teds_bitvector_it*)iter)->dllist_node;
teds_intrusive_dllist_remove(&Z_BITVECTOR_ENTRIES_P(&iter->data)->active_iterators, node);
zval_ptr_dtor(&iter->data);
}
static void teds_bitvector_it_rewind(zend_object_iterator *iter)
{
((teds_bitvector_it*)iter)->current = 0;
}
static int teds_bitvector_it_valid(zend_object_iterator *iter)
{
teds_bitvector_it *iterator = (teds_bitvector_it*)iter;
teds_bitvector *object = Z_BITVECTOR_P(&iter->data);
if (iterator->current < object->array.bit_size) {
return SUCCESS;
}
return FAILURE;
}
static zval *teds_bitvector_it_get_current_data(zend_object_iterator *iter)
{
teds_bitvector_it *iterator = (teds_bitvector_it*)iter;
teds_bitvector_entries *array = Z_BITVECTOR_ENTRIES_P(&iter->data);
if (UNEXPECTED(iterator->current >= array->bit_size)) {
teds_throw_invalid_sequence_index_exception();
return &EG(uninitialized_zval);
}
return teds_bitvector_entries_read_offset(array, iterator->current, &iterator->tmp);
}
static void teds_bitvector_it_get_current_key(zend_object_iterator *iter, zval *key)
{
teds_bitvector_it *iterator = (teds_bitvector_it*)iter;
teds_bitvector *object = Z_BITVECTOR_P(&iter->data);
size_t offset = iterator->current;
if (offset >= object->array.bit_size) {
ZVAL_NULL(key);
} else {
ZVAL_LONG(key, offset);
}
}
static void teds_bitvector_it_move_forward(zend_object_iterator *iter)
{
((teds_bitvector_it*)iter)->current++;
}
/* iterator handler table */
static const zend_object_iterator_funcs teds_bitvector_it_funcs = {
teds_bitvector_it_dtor,
teds_bitvector_it_valid,
teds_bitvector_it_get_current_data,
teds_bitvector_it_get_current_key,
teds_bitvector_it_move_forward,
teds_bitvector_it_rewind,
NULL,
NULL, /* get_gc */
};
static void teds_bitvector_adjust_iterators_before_remove(teds_bitvector_entries *array, teds_intrusive_dllist_node *node, const size_t removed_offset)
{
const size_t old_size = array->bit_size;
const zend_object *const obj = teds_bitvector_to_object(array);
ZEND_ASSERT(removed_offset < old_size);
do {
teds_bitvector_it *it = teds_bitvector_it_from_node(node);
if (Z_OBJ(it->intern.data) == obj) {
if (it->current >= removed_offset && it->current < old_size) {
it->current--;
}
}
ZEND_ASSERT(node != node->next);
node = node->next;
} while (node != NULL);
}
static zend_always_inline void teds_bitvector_maybe_adjust_iterators_before_remove(teds_bitvector_entries *array, const size_t removed_offset)
{
teds_intrusive_dllist_node *iterator = array->active_iterators.first;
if (UNEXPECTED(iterator)) {
teds_bitvector_adjust_iterators_before_remove(array, iterator, removed_offset);
}
}
static void teds_bitvector_adjust_iterators_before_insert(teds_bitvector_entries *const array, teds_intrusive_dllist_node *node, const size_t inserted_offset, const uint32_t n)
{
const zend_object *const obj = teds_bitvector_to_object(array);
const size_t old_size = array->bit_size;
ZEND_ASSERT(inserted_offset <= old_size);
do {
teds_bitvector_it *it = teds_bitvector_it_from_node(node);
if (Z_OBJ(it->intern.data) == obj) {
if (it->current >= inserted_offset && it->current < old_size) {
it->current += n;
}
}
ZEND_ASSERT(node != node->next);
node = node->next;
} while (node != NULL);
}
static zend_always_inline void teds_bitvector_maybe_adjust_iterators_before_insert(teds_bitvector_entries *const array, const size_t inserted_offset, const uint32_t n)
{
teds_intrusive_dllist_node *iterator = array->active_iterators.first;
if (UNEXPECTED(iterator)) {
teds_bitvector_adjust_iterators_before_insert(array, iterator, inserted_offset, n);
}
}
zend_object_iterator *teds_bitvector_get_iterator(zend_class_entry *ce, zval *object, int by_ref)
{
// This is final
ZEND_ASSERT(ce == teds_ce_BitVector);
teds_bitvector_it *iterator;
if (UNEXPECTED(by_ref)) {
zend_throw_error(NULL, "An iterator cannot be used with foreach by reference");
return NULL;
}
iterator = emalloc(sizeof(teds_bitvector_it));
zend_iterator_init((zend_object_iterator*)iterator);
zend_object *obj = Z_OBJ_P(object);
ZVAL_OBJ_COPY(&iterator->intern.data, obj);
iterator->intern.funcs = &teds_bitvector_it_funcs;
teds_intrusive_dllist_prepend(&teds_bitvector_from_object(obj)->array.active_iterators, &iterator->dllist_node);
return &iterator->intern;
}
static void teds_bitvector_initialize_from_bytes(teds_bitvector_entries *array, const uint8_t *bytes, const size_t byte_count, const uint8_t modulo_bit_len)
{
const size_t bit_size = byte_count * 8 - modulo_bit_len;
ZEND_ASSERT(bit_size > 0);
const size_t bit_capacity = teds_bitvector_compute_next_valid_capacity(bit_size);
// fprintf(stderr, "byte_count=%d modulo_bit_len=%d bit_size=%d bit_capacity=%d\n", (int)byte_count, (int)modulo_bit_len, (int)bit_size, (int)bit_capacity);
uint8_t *const bytes_copy = emalloc(bit_capacity >> 3);
memcpy(bytes_copy, bytes, byte_count);
array->entries_bits = bytes_copy;
array->bit_size = bit_size;
array->bit_capacity = bit_capacity;
}
PHP_METHOD(Teds_BitVector, __unserialize)
{
HashTable *raw_data;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "h", &raw_data) == FAILURE) {
RETURN_THROWS();
}
teds_bitvector_entries *array = Z_BITVECTOR_ENTRIES_P(ZEND_THIS);
if (UNEXPECTED(!teds_bitvector_entries_uninitialized(array))) {
zend_throw_exception(spl_ce_RuntimeException, "Teds\\BitVector already unserialized", 0);
RETURN_THROWS();
}
if (zend_hash_num_elements(raw_data) == 0) {
teds_bitvector_entries_set_empty_list(array);
return;
}
if (UNEXPECTED(zend_hash_num_elements(raw_data) != 1)) {
zend_throw_exception(spl_ce_RuntimeException, "Teds\\BitVector unexpected __unserialize data: expected exactly 0 or 1 value", 0);
RETURN_THROWS();
}
const zval *const raw_zval = zend_hash_index_find(raw_data, 0);
if (UNEXPECTED(raw_zval == NULL)) {
zend_throw_exception(spl_ce_RuntimeException, "Teds\\BitVector missing data to unserialize", 0);
RETURN_THROWS();
}
if (Z_TYPE_P(raw_zval) != IS_STRING) {
zend_throw_exception(spl_ce_RuntimeException, "Teds\\BitVector expected string for binary data", 0);
RETURN_THROWS();
}
const zend_string *const zstr = Z_STR_P(raw_zval);
if (ZSTR_LEN(zstr) == 0) {
// Not expected but allowed
teds_bitvector_entries_set_empty_list(array);
return;
}
const uint8_t *bytes = (const uint8_t *)ZSTR_VAL(zstr);
const size_t byte_count = ZSTR_LEN(zstr) - 1;
const uint8_t modulo_bit_len = (uint8_t) bytes[byte_count];
if (modulo_bit_len >= 8) {
zend_throw_exception(spl_ce_RuntimeException, "Teds\\BitVector expected binary data to end with number of wasted bits", 0);
RETURN_THROWS();
}
teds_bitvector_initialize_from_bytes(array, bytes, byte_count, modulo_bit_len);
TEDS_RETURN_VOID();
}
static zend_always_inline zend_string *teds_create_string_from_entries_int8(const char *raw, const size_t len) {
return zend_string_init(raw, len, 0);
}
static zend_always_inline zend_string *teds_create_string_from_entries_int16(const char *raw, const size_t len) {
#ifdef WORDS_BIGENDIAN
zend_string *const result = zend_string_alloc(len * sizeof(int16_t), 0);
uint16_t *dst = (uint16_t *)ZSTR_VAL(result);
const uint16_t *src = (const uint16_t *)raw;
const uint16_t *const end = src + len;
for (;src < end; src++, dst++) {
const uint16_t v = *src;
*dst = teds_bswap_16(*src);
}
*(char *)dst = '\0';
return result;
#else
return zend_string_init(raw, len * sizeof(int16_t), 0);
#endif
}
static zend_always_inline zend_string *teds_create_string_from_entries_int32(const char *raw, const size_t len) {
#ifdef WORDS_BIGENDIAN
zend_string *const result = zend_string_alloc(len * sizeof(int32_t), 0);
uint32_t *dst = (uint32_t *)ZSTR_VAL(result);
const uint32_t *src = (const uint32_t *)raw;
const uint32_t *const end = src + len;
for (;src < end; src++, dst++) {
/* This compiles down to a bswap assembly instruction in optimized builds */
*dst = bswap_32(*src);
}
*(char *)dst = '\0';
return result;
#else
return zend_string_init(raw, len * sizeof(int32_t), 0);
#endif
}
static zend_always_inline zend_string *teds_create_string_from_entries_int64(const char *raw, const size_t len) {
#ifdef WORDS_BIGENDIAN
zend_string *const result = zend_string_alloc(len * sizeof(int64_t), 0);
uint64_t *dst = (uint64_t *)ZSTR_VAL(result);
const uint64_t *src = (const uint64_t *)raw;
const uint64_t *const end = src + len;
for (;src < end; src++, dst++) {
/* This compiles down to a bswap assembly instruction in optimized builds */
*dst = bswap_64(*src);
}
*(char *)dst = '\0';
return result;
#else
return zend_string_init(raw, len * sizeof(int64_t), 0);
#endif
}
static zend_string *teds_bitvector_create_serialized_string(const teds_bitvector_entries *const array)
{
const size_t len = array->bit_size;
const uint8_t removed_bits = ((8 - len) & 7);
const size_t str_len = BYTES_FOR_BIT_SIZE(len);
const uint8_t mask = ((1 << (8 - removed_bits)) - 1);
// fprintf(stderr, "serialize mask=%d str_len=%d len=%d removed=%d\n", (int)mask, (int)str_len, (int)len, (int)removed_bits);
zend_string *const ret = zend_string_alloc(str_len + 1, 0);
memcpy(ZSTR_VAL(ret), array->entries_bits, str_len);
ZSTR_VAL(ret)[str_len - 1] &= mask;
ZSTR_VAL(ret)[str_len] = removed_bits;
ZSTR_VAL(ret)[str_len + 1] = '\0';
return ret;
}
static zend_string *teds_bitvector_create_serialized_string_no_padding(const teds_bitvector_entries *const array)
{
const size_t len = array->bit_size;
const uint8_t removed_bits = ((8 - len) & 7);
const size_t str_len = BYTES_FOR_BIT_SIZE(len);
const uint8_t mask = ((1 << (8 - removed_bits)) - 1);
zend_string *const ret = zend_string_alloc(str_len, 0);
memcpy(ZSTR_VAL(ret), array->entries_bits, str_len);
ZSTR_VAL(ret)[str_len - 1] &= mask;
ZSTR_VAL(ret)[str_len] = '\0';
return ret;
}
PHP_METHOD(Teds_BitVector, __serialize)
{
ZEND_PARSE_PARAMETERS_NONE();
const teds_bitvector_entries *const array = Z_BITVECTOR_ENTRIES_P(ZEND_THIS);
const size_t len = array->bit_size;
if (len == 0) {
RETURN_EMPTY_ARRAY();
}
/* Represent the bitvector as the bytes, followed by the number of bits % 8 */
zval tmp;
ZVAL_STR(&tmp, teds_bitvector_create_serialized_string(array));
zend_array *result = zend_new_array(1);
zend_hash_next_index_insert(result, &tmp);
RETURN_ARR(result);
}
PHP_METHOD(Teds_BitVector, serialize)
{
ZEND_PARSE_PARAMETERS_NONE();
const teds_bitvector_entries *const array = Z_BITVECTOR_ENTRIES_P(ZEND_THIS);
const size_t len = array->bit_size;
if (len == 0) {
RETURN_EMPTY_STRING();
}
RETURN_STR(teds_bitvector_create_serialized_string(array));
}
PHP_METHOD(Teds_BitVector, unserialize)
{
zend_string *zstr;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(zstr)
ZEND_PARSE_PARAMETERS_END();
zend_object *new_object = teds_bitvector_new(teds_ce_BitVector);
teds_bitvector *bitvector = teds_bitvector_from_object(new_object);
if (ZSTR_LEN(zstr) == 0) {
teds_bitvector_entries_set_empty_list(&bitvector->array);
} else {
const uint8_t *bytes = (const uint8_t *)ZSTR_VAL(zstr);
const size_t byte_count = ZSTR_LEN(zstr) - 1;
const uint8_t modulo_bit_len = (uint8_t) bytes[byte_count];
if (modulo_bit_len >= 8) {
zend_throw_exception(spl_ce_RuntimeException, "Teds\\BitVector expected binary data to end with number of wasted bits", 0);
RETURN_THROWS();
}
teds_bitvector_initialize_from_bytes(&bitvector->array, bytes, byte_count, modulo_bit_len);
}
RETURN_OBJ(new_object);
}
PHP_METHOD(Teds_BitVector, toBinaryString)
{
ZEND_PARSE_PARAMETERS_NONE();
const teds_bitvector_entries *const array = Z_BITVECTOR_ENTRIES_P(ZEND_THIS);
const size_t len = array->bit_size;
if (len == 0) {
RETURN_EMPTY_STRING();
}
RETURN_STR(teds_bitvector_create_serialized_string_no_padding(array));
}
PHP_METHOD(Teds_BitVector, fromBinaryString)
{
zend_string *zstr;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(zstr)
ZEND_PARSE_PARAMETERS_END();
zend_object *new_object = teds_bitvector_new(teds_ce_BitVector);
teds_bitvector *bitvector = teds_bitvector_from_object(new_object);
if (ZSTR_LEN(zstr) == 0) {
teds_bitvector_entries_set_empty_list(&bitvector->array);
} else {
const uint8_t *bytes = (const uint8_t *)ZSTR_VAL(zstr);
const size_t byte_count = ZSTR_LEN(zstr);
teds_bitvector_initialize_from_bytes(&bitvector->array, bytes, byte_count, 0);
}
RETURN_OBJ(new_object);
}
static void teds_bitvector_entries_init_from_array_values(teds_bitvector_entries *array, zend_array *raw_data)
{
const size_t num_entries = zend_hash_num_elements(raw_data);
teds_bitvector_entries_set_empty_list(array);
if (num_entries == 0) {
return;
}
/* Precompute bit_capacity to avoid reallocations/branches */
const size_t bytes_needed = BYTES_FOR_BIT_SIZE(num_entries);
array->entries_bits = emalloc(bytes_needed);
array->bit_capacity = bytes_needed * 8;
zval *val_zv;
ZEND_HASH_FOREACH_VAL(raw_data, val_zv) {
zend_long val;
TEDS_BITVECTOR_VALUE_TO_BOOL_OR_THROW(val, val_zv);
teds_bitvector_entries_push(array, val, 0);
} ZEND_HASH_FOREACH_END();
}
PHP_METHOD(Teds_BitVector, __set_state)
{
zend_array *array_ht;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY_HT(array_ht)
ZEND_PARSE_PARAMETERS_END();
zend_object *object = teds_bitvector_new(teds_ce_BitVector);
teds_bitvector *intern = teds_bitvector_from_object(object);
teds_bitvector_entries_init_from_array_values(&intern->array, array_ht);
RETURN_OBJ(object);
}
static zend_array *teds_bitvector_entries_to_refcounted_array(const teds_bitvector_entries *array) {
const size_t len = array->bit_size;
const uint8_t *const bit_values = array->entries_bits;
zend_array *const values = teds_new_array_check_overflow(len);
/* Initialize return array */
zend_hash_real_init_packed(values);
/* Go through values and add values to the return array */
ZEND_HASH_FILL_PACKED(values) {
for (size_t i = 0; i < len; i++) {
ZVAL_BOOL(__teds_fill_val, ((bit_values[i >> 3] >> (i & 7)) & 1));
ZEND_HASH_FILL_NEXT();
}
} ZEND_HASH_FILL_END();
return values;
}
PHP_METHOD(Teds_BitVector, toArray)
{
ZEND_PARSE_PARAMETERS_NONE();
const teds_bitvector_entries *array = Z_BITVECTOR_ENTRIES_P(ZEND_THIS);
size_t len = array->bit_size;
if (!len) {
RETURN_EMPTY_ARRAY();
}
RETURN_ARR(teds_bitvector_entries_to_refcounted_array(array));
}
static zend_always_inline void teds_bitvector_convert_zval_value_to_long_at_offset(zval *return_value, const zval *zval_this, zend_long offset)
{
teds_bitvector_entries *array = Z_BITVECTOR_ENTRIES_P(zval_this);
size_t len = array->bit_size;
if (UNEXPECTED((zend_ulong) offset >= len)) {
teds_throw_invalid_sequence_index_exception();
RETURN_THROWS();
}
teds_bitvector_entries_copy_offset(array, offset, return_value, false);
}
PHP_METHOD(Teds_BitVector, get)
{
zend_long offset;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_LONG(offset)
ZEND_PARSE_PARAMETERS_END();
teds_bitvector_convert_zval_value_to_long_at_offset(return_value, ZEND_THIS, offset);
}
PHP_METHOD(Teds_BitVector, offsetGet)
{
zval *offset_zv;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(offset_zv)
ZEND_PARSE_PARAMETERS_END();
zend_long offset;
CONVERT_OFFSET_TO_LONG_OR_THROW(offset, offset_zv);
teds_bitvector_convert_zval_value_to_long_at_offset(return_value, ZEND_THIS, offset);
}
PHP_METHOD(Teds_BitVector, offsetExists)
{
zval *offset_zv;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(offset_zv)
ZEND_PARSE_PARAMETERS_END();
zend_long offset;
CONVERT_OFFSET_TO_LONG_OR_THROW(offset, offset_zv);
RETURN_BOOL((zend_ulong) offset < Z_BITVECTOR_ENTRIES_P(ZEND_THIS)->bit_size);
}
/* containsKey is similar to offsetExists but rejects non-integers */
PHP_METHOD(Teds_BitVector, containsKey)
{
zval *offset_zv;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(offset_zv)
ZEND_PARSE_PARAMETERS_END();
if (Z_TYPE_P(offset_zv) != IS_LONG) {
RETURN_FALSE;
}
zend_long offset = Z_LVAL_P(offset_zv);
RETURN_BOOL((zend_ulong) offset < Z_BITVECTOR_ENTRIES_P(ZEND_THIS)->bit_size);
}
PHP_METHOD(Teds_BitVector, indexOf)
{
bool value;
ZEND_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_BOOL(value)
ZEND_PARSE_PARAMETERS_END();
const teds_bitvector_entries *array = Z_BITVECTOR_ENTRIES_P(ZEND_THIS);
const size_t len = array->bit_size;
if (len == 0) {
RETURN_NULL();
}
const uint8_t *const entries_bits = array->entries_bits;
size_t i = 0;
while (i + 64 <= len) {
if ((*(uint64_t *)&entries_bits[i >> 3]) + value) {
break;
}
i += 64;
}
while (i + 8 <= len) {
if ((uint8_t)(entries_bits[i >> 3] + value)) {
break;
}
i += 8;
}
// TODO: builtin_clz?
uint8_t v = entries_bits[i >> 3] + value;
while (i < len) {
if (v & 1) {
RETURN_LONG(i);