-
Notifications
You must be signed in to change notification settings - Fork 29
/
_base.py
1595 lines (1349 loc) · 48.3 KB
/
_base.py
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 2011 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Python BTree implementation
"""
from struct import Struct
from struct import error as struct_error
from operator import index
from persistent import Persistent
from .Interfaces import BTreesConflictError
from ._compat import PY3
from ._compat import compare
from ._compat import int_types
from ._compat import xrange
_marker = object()
class _Base(Persistent):
__slots__ = ()
_key_type = list
def __init__(self, items=None):
self.clear()
if items:
self.update(items)
try:
# Detect the presence of the C extensions.
# If they're NOT around, we don't need to do any of the
# special pickle support to make Python versions look like
# C---we just rename the classes. By not defining these methods,
# we can (theoretically) avoid a bit of a slowdown.
# If the C extensions are around, we do need these methods, but
# these classes are unlikely to be used in production anyway.
__import__('BTrees._OOBTree')
except ImportError: # pragma: no cover
pass
else:
def __reduce__(self):
# Swap out the type constructor for the C version, if present.
func, typ_gna, state = Persistent.__reduce__(self)
# We ignore the returned type altogether in favor of
# our calculated class (which allows subclasses but replaces our exact
# type with the C equivalent)
typ = self.__class__
gna = typ_gna[1:]
return (func, (typ,) + gna, state)
@property
def __class__(self):
type_self = type(self)
return type_self._BTree_reduce_as if type_self._BTree_reduce_up_bound is type_self else type_self
@property
def _BTree_reduce_as(self):
# Return the pickle replacement class for this object.
# If the C extensions are available, this will be the
# C type (setup by _fix_pickle), otherwise it will be the real
# type of this object.
# This implementation is replaced by _fix_pickle and exists for
# testing purposes.
return type(self) # pragma: no cover
_BTree_reduce_up_bound = _BTree_reduce_as
class _BucketBase(_Base):
__slots__ = ('_keys',
'_next',
'_to_key',
)
def clear(self):
self._keys = self._key_type()
self._next = None
def __len__(self):
return len(self._keys)
@property
def size(self):
return len(self._keys)
def _deleteNextBucket(self):
next = self._next
if next is not None:
self._next = next._next
def _search(self, key):
# Return non-negative index on success
# return -(insertion_index + 1) on fail
low = 0
keys = self._keys
high = len(keys)
while low < high:
i = (low + high) // 2
k = keys[i]
if k is key or k == key:
return i
if compare(k, key) < 0:
low = i + 1
else:
high = i
return -1 - low
def minKey(self, key=_marker):
if key is _marker or key is None:
return self._keys[0]
key = self._to_key(key)
index = self._search(key)
if index >= 0:
return key
index = -index - 1
if index < len(self._keys):
return self._keys[index]
else:
raise ValueError("no key satisfies the conditions")
def maxKey(self, key=_marker):
if key is _marker or key is None:
return self._keys[-1]
key = self._to_key(key)
index = self._search(key)
if index >= 0:
return key
else:
index = -index-1
if index:
return self._keys[index-1]
else:
raise ValueError("no key satisfies the conditions")
def _range(self, min=_marker, max=_marker,
excludemin=False, excludemax=False):
if min is _marker or min is None:
start = 0
if excludemin:
start = 1
else:
min = self._to_key(min)
start = self._search(min)
if start >= 0:
if excludemin:
start += 1
else:
start = -start - 1
if max is _marker or max is None:
end = len(self._keys)
if excludemax:
end -= 1
else:
max = self._to_key(max)
end = self._search(max)
if end >= 0:
if not excludemax:
end += 1
else:
end = -end - 1
return start, end
def keys(self, *args, **kw):
start, end = self._range(*args, **kw)
return self._keys[start:end]
def iterkeys(self, *args, **kw):
if not (args or kw):
return iter(self._keys)
keys = self._keys
return (keys[i] for i in xrange(*self._range(*args, **kw)))
def __iter__(self):
return iter(self._keys)
def __contains__(self, key):
return (self._search(self._to_key(key)) >= 0)
has_key = __contains__
def _repr_helper(self, items):
type_self = type(self)
mod = type_self.__module__
name = type_self.__name__
name = name[:-2] if name.endswith("Py") else name
return "%s.%s(%r)" % (mod, name, items)
class _SetIteration(object):
__slots__ = ('to_iterate',
'useValues',
'_iter',
'active',
'position',
'key',
'value',
)
def __init__(self, to_iterate, useValues=False, default=None):
if to_iterate is None:
to_iterate = ()
self.to_iterate = to_iterate
if useValues:
try:
itmeth = to_iterate.iteritems
except AttributeError:
if PY3 and isinstance(to_iterate, dict): #pragma no cover Py3k
itmeth = to_iterate.items().__iter__
else:
itmeth = to_iterate.__iter__
useValues = False
else:
self.value = None
else:
itmeth = to_iterate.__iter__
self.useValues = useValues
self._iter = itmeth()
self.active = True
self.position = 0
self.key = _marker
self.value = default
self.advance()
def advance(self):
try:
if self.useValues:
self.key, self.value = next(self._iter)
else:
self.key = next(self._iter)
self.position += 1
except StopIteration:
self.active = False
self.position = -1
return self
_object_lt = getattr(object, '__lt__', _marker)
def _no_default_comparison(key):
# Enforce test that key has non-default comparison.
if key is None:
return
if type(key) is object:
raise TypeError("Can't use object() as keys")
lt = getattr(key, '__lt__', None)
if lt is not None:
# CPython 3.x follows PEP 252, defining '__objclass__'
if getattr(lt, '__objclass__', None) is object:
lt = None # pragma: no cover Py3k
# PyPy3 doesn't follow PEP 252, but defines '__func__'
elif getattr(lt, '__func__', None) is _object_lt:
lt = None # pragma: no cover PyPy3
if (lt is None and
getattr(key, '__cmp__', None) is None):
raise TypeError("Object has default comparison")
class Bucket(_BucketBase):
__slots__ = ()
_value_type = list
_to_value = lambda self, x: x
VALUE_SAME_CHECK = False
def setdefault(self, key, value):
key, value = self._to_key(key), self._to_value(value)
status, value = self._set(key, value, True)
return value
def pop(self, key, default=_marker):
try:
status, value = self._del(self._to_key(key))
except KeyError:
if default is _marker:
raise
return default
else:
return value
def update(self, items):
if hasattr(items, 'iteritems'):
items = items.iteritems()
elif hasattr(items, 'items'):
items = items.items()
_si = self.__setitem__
try:
for key, value in items:
_si(key, value)
except ValueError:
raise TypeError('items must be a sequence of 2-tuples')
def __setitem__(self, key, value):
_no_default_comparison(key)
self._set(self._to_key(key), self._to_value(value))
def __delitem__(self, key):
self._del(self._to_key(key))
def clear(self):
_BucketBase.clear(self)
self._values = self._value_type()
def get(self, key, default=None):
index = self._search(self._to_key(key))
if index < 0:
return default
return self._values[index]
def __getitem__(self, key):
index = self._search(self._to_key(key))
if index < 0:
raise KeyError(key)
return self._values[index]
def _set(self, key, value, ifunset=False):
"""Set a value
Return: status, value
Status is:
None if no change
0 if change, but not size change
1 if change and size change
"""
index = self._search(key)
if index >= 0:
if (ifunset or
self.VALUE_SAME_CHECK and value == self._values[index]
):
return None, self._values[index]
self._p_changed = True
self._values[index] = value
return 0, value
else:
self._p_changed = True
index = -index - 1
self._keys.insert(index, key)
self._values.insert(index, value)
return 1, value
def _del(self, key):
index = self._search(key)
if index >= 0:
self._p_changed = True
del self._keys[index]
return 0, self._values.pop(index)
raise KeyError(key)
def _split(self, index=-1):
if index < 0 or index >= len(self._keys):
index = len(self._keys) // 2
new_instance = type(self)()
new_instance._keys = self._keys[index:]
new_instance._values = self._values[index:]
del self._keys[index:]
del self._values[index:]
new_instance._next = self._next
self._next = new_instance
return new_instance
def values(self, *args, **kw):
start, end = self._range(*args, **kw)
return self._values[start:end]
def itervalues(self, *args, **kw):
values = self._values
return (values[i] for i in xrange(*self._range(*args, **kw)))
def items(self, *args, **kw):
keys = self._keys
values = self._values
return [(keys[i], values[i])
for i in xrange(*self._range(*args, **kw))]
def iteritems(self, *args, **kw):
keys = self._keys
values = self._values
return ((keys[i], values[i])
for i in xrange(*self._range(*args, **kw)))
def __getstate__(self):
keys = self._keys
values = self._values
data = []
for i in range(len(keys)):
data.append(keys[i])
data.append(values[i])
data = tuple(data)
if self._next is not None:
return data, self._next
return (data, )
def __setstate__(self, state):
if not isinstance(state[0], tuple):
raise TypeError("tuple required for first state element")
self.clear()
if len(state) == 2:
state, self._next = state
else:
self._next = None
state = state[0]
keys = self._keys
values = self._values
for i in range(0, len(state), 2):
keys.append(state[i])
values.append(state[i+1])
def _p_resolveConflict(self, s_old, s_com, s_new):
b_old = type(self)()
if s_old is not None:
b_old.__setstate__(s_old)
b_com = type(self)()
if s_com is not None:
b_com.__setstate__(s_com)
b_new = type(self)()
if s_new is not None:
b_new.__setstate__(s_new)
if (b_com._next != b_old._next or
b_new._next != b_old._next):
raise BTreesConflictError(-1, -1, -1, 0)
if not b_com or not b_new:
raise BTreesConflictError(-1, -1, -1, 12)
i_old = _SetIteration(b_old, True)
i_com = _SetIteration(b_com, True)
i_new = _SetIteration(b_new, True)
def merge_error(reason):
return BTreesConflictError(
i_old.position, i_com.position, i_new.position, reason)
result = type(self)()
def merge_output(it):
result._keys.append(it.key)
result._values.append(it.value)
it.advance()
while i_old.active and i_com.active and i_new.active:
cmpOC = compare(i_old.key, i_com.key)
cmpON = compare(i_old.key, i_new.key)
if cmpOC == 0:
if cmpON == 0:
if i_com.value == i_old.value:
result[i_old.key] = i_new.value
elif i_new.value == i_old.value:
result[i_old.key] = i_com.value
else:
raise merge_error(1)
i_old.advance()
i_com.advance()
i_new.advance()
elif (cmpON > 0): # insert in new
merge_output(i_new)
elif i_old.value == i_com.value: # deleted new
if i_new.position == 1:
# Deleted the first item. This will modify the
# parent node, so we don't know if merging will be
# safe
raise merge_error(13)
i_old.advance()
i_com.advance()
else:
raise merge_error(2)
elif cmpON == 0:
if cmpOC > 0: # insert committed
merge_output(i_com)
elif i_old.value == i_new.value: # delete committed
if i_com.position == 1:
# Deleted the first item. This will modify the
# parent node, so we don't know if merging will be
# safe
raise merge_error(13)
i_old.advance()
i_new.advance()
else:
raise merge_error(3)
else: # both keys changed
cmpCN = compare(i_com.key, i_new.key)
if cmpCN == 0: # dueling insert
raise merge_error(4)
if cmpOC > 0: # insert committed
if cmpCN > 0: # insert i_new first
merge_output(i_new)
else:
merge_output(i_com)
elif cmpON > 0: # insert i_new
merge_output(i_new)
else:
raise merge_error(5) # both deleted same key
while i_com.active and i_new.active: # new inserts
cmpCN = compare(i_com.key, i_new.key)
if cmpCN == 0:
raise merge_error(6) # dueling insert
if cmpCN > 0: # insert new
merge_output(i_new)
else: # insert committed
merge_output(i_com)
while i_old.active and i_com.active: # new deletes rest of original
cmpOC = compare(i_old.key, i_com.key)
if cmpOC > 0: # insert committed
merge_output(i_com)
elif cmpOC == 0 and (i_old.value == i_com.value): # del in new
i_old.advance()
i_com.advance()
else: # dueling deletes or delete and change
raise merge_error(7)
while i_old.active and i_new.active:
# committed deletes rest of original
cmpON = compare(i_old.key, i_new.key)
if cmpON > 0: # insert new
merge_output(i_new)
elif cmpON == 0 and (i_old.value == i_new.value):
# deleted in committed
i_old.advance()
i_new.advance()
else: # dueling deletes or delete and change
raise merge_error(8)
if i_old.active: # dueling deletes
raise merge_error(9)
while i_com.active:
merge_output(i_com)
while i_new.active:
merge_output(i_new)
if len(result._keys) == 0: #pragma: no cover
# If the output bucket is empty, conflict resolution doesn't have
# enough info to unlink it from its containing BTree correctly.
#
# XXX TS, 2012-11-16: I don't think this is possible
#
raise merge_error(10)
result._next = b_old._next
return result.__getstate__()
def __repr__(self):
return self._repr_helper(self.items())
class Set(_BucketBase):
__slots__ = ()
def add(self, key):
return self._set(self._to_key(key))[0]
insert = add
def remove(self, key):
self._del(self._to_key(key))
def update(self, items):
add = self.add
for i in items:
add(i)
def __getstate__(self):
data = tuple(self._keys)
if self._next is not None:
return data, self._next
return (data, )
def __setstate__(self, state):
if not isinstance(state[0], tuple):
raise TypeError('tuple required for first state element')
self.clear()
if len(state) == 2:
state, self._next = state
else:
self._next = None
state = state[0]
self._keys.extend(state)
def _set(self, key, value=None, ifunset=False):
index = self._search(key)
if index < 0:
index = -index - 1
self._p_changed = True
self._keys.insert(index, key)
return True, None
return False, None
def _del(self, key):
index = self._search(key)
if index >= 0:
self._p_changed = True
del self._keys[index]
return 0, 0
raise KeyError(key)
def __getitem__(self, i):
return self._keys[i]
def _split(self, index=-1):
if index < 0 or index >= len(self._keys):
index = len(self._keys) // 2
new_instance = type(self)()
new_instance._keys = self._keys[index:]
del self._keys[index:]
new_instance._next = self._next
self._next = new_instance
return new_instance
def _p_resolveConflict(self, s_old, s_com, s_new):
b_old = type(self)()
if s_old is not None:
b_old.__setstate__(s_old)
b_com = type(self)()
if s_com is not None:
b_com.__setstate__(s_com)
b_new = type(self)()
if s_new is not None:
b_new.__setstate__(s_new)
if (b_com._next != b_old._next or
b_new._next != b_old._next): # conflict: com or new changed _next
raise BTreesConflictError(-1, -1, -1, 0)
if not b_com or not b_new: # conflict: com or new empty
raise BTreesConflictError(-1, -1, -1, 12)
i_old = _SetIteration(b_old, True)
i_com = _SetIteration(b_com, True)
i_new = _SetIteration(b_new, True)
def merge_error(reason):
return BTreesConflictError(
i_old.position, i_com.position, i_new.position, reason)
result = type(self)()
def merge_output(it):
result._keys.append(it.key)
it.advance()
while i_old.active and i_com.active and i_new.active:
cmpOC = compare(i_old.key, i_com.key)
cmpON = compare(i_old.key, i_new.key)
if cmpOC == 0:
if cmpON == 0: # all match
merge_output(i_old)
i_com.advance()
i_new.advance()
elif cmpON > 0: # insert in new
merge_output(i_new)
else: # deleted new
if i_new.position == 1:
# Deleted the first item. This will modify the
# parent node, so we don't know if merging will be
# safe
raise merge_error(13)
i_old.advance()
i_com.advance()
elif cmpON == 0:
if cmpOC > 0: # insert committed
merge_output(i_com)
else: # delete committed
if i_com.position == 1:
# Deleted the first item. This will modify the
# parent node, so we don't know if merging will be
# safe
raise merge_error(13)
i_old.advance()
i_new.advance()
else: # both com and new keys changed
cmpCN = compare(i_com.key, i_new.key)
if cmpCN == 0: # both inserted same key
raise merge_error(4)
if cmpOC > 0: # insert committed
if cmpCN > 0: # insert i_new first
merge_output(i_new)
else:
merge_output(i_com)
elif cmpON > 0: # insert i_new
merge_output(i_new)
else: # both com and new deleted same key
raise merge_error(5)
while i_com.active and i_new.active: # new inserts
cmpCN = compare(i_com.key, i_new.key)
if cmpCN == 0: # dueling insert
raise merge_error(6)
if cmpCN > 0: # insert new
merge_output(i_new)
else: # insert committed
merge_output(i_com)
while i_old.active and i_com.active: # new deletes rest of original
cmpOC = compare(i_old.key, i_com.key)
if cmpOC > 0: # insert committed
merge_output(i_com)
elif cmpOC == 0: # del in new
i_old.advance()
i_com.advance()
else: # dueling deletes or delete and change
raise merge_error(7)
while i_old.active and i_new.active:
# committed deletes rest of original
cmpON = compare(i_old.key, i_new.key)
if cmpON > 0: # insert new
merge_output(i_new)
elif cmpON == 0: # deleted in committed
i_old.advance()
i_new.advance()
else: # dueling deletes or delete and change
raise merge_error(8)
if i_old.active: # dueling deletes
raise merge_error(9)
while i_com.active:
merge_output(i_com)
while i_new.active:
merge_output(i_new)
if len(result._keys) == 0: #pragma: no cover
# If the output bucket is empty, conflict resolution doesn't have
# enough info to unlink it from its containing BTree correctly.
#
# XXX TS, 2012-11-16: I don't think this is possible
#
raise merge_error(10)
result._next = b_old._next
return result.__getstate__()
def __repr__(self):
return self._repr_helper(self._keys)
class _TreeItem(object):
__slots__ = ('key',
'child',
)
def __init__(self, key, child):
self.key = key
self.child = child
class _Tree(_Base):
__slots__ = ('_data',
'_firstbucket',
)
def __new__(cls, *args):
value = _Base.__new__(cls, *args)
# Empty trees don't get their __setstate__ called upon
# unpickling (or __init__, obviously), so clear() is never called
# and _data and _firstbucket are never defined, unless we do it here.
value._data = []
value._firstbucket = None
return value
def setdefault(self, key, value):
return self._set(self._to_key(key), self._to_value(value), True)[1]
def pop(self, key, default=_marker):
try:
return self._del(self._to_key(key))[1]
except KeyError:
if default is _marker:
raise
return default
def update(self, items):
if hasattr(items, 'iteritems'):
items = items.iteritems()
elif hasattr(items, 'items'):
items = items.items()
set = self.__setitem__
for i in items:
set(*i)
def __setitem__(self, key, value):
_no_default_comparison(key)
self._set(self._to_key(key), self._to_value(value))
def __delitem__(self, key):
self._del(self._to_key(key))
def clear(self):
if self._data:
# In the case of __init__, this was already set by __new__
self._data = []
self._firstbucket = None
def __nonzero__(self):
return bool(self._data)
__bool__ = __nonzero__ #Py3k rename
def __len__(self):
l = 0
bucket = self._firstbucket
while bucket is not None:
l += len(bucket._keys)
bucket = bucket._next
return l
@property
def size(self):
return len(self._data)
def _search(self, key):
data = self._data
if data:
lo = 0
hi = len(data)
i = hi // 2
while i > lo:
cmp_ = compare(data[i].key, key)
if cmp_ < 0:
lo = i
elif cmp_ > 0:
hi = i
else:
break
i = (lo + hi) // 2
return i
return -1
def _findbucket(self, key):
index = self._search(key)
if index >= 0:
child = self._data[index].child
if isinstance(child, self._bucket_type):
return child
return child._findbucket(key)
def __contains__(self, key):
try:
tree_key = self._to_key(key)
except TypeError:
# Can't convert the key, so can't possibly be in the tree
return False
return key in (self._findbucket(tree_key) or ())
def has_key(self, key):
index = self._search(key)
if index < 0:
return False
r = self._data[index].child.has_key(key)
return r and r + 1
def keys(self, min=_marker, max=_marker,
excludemin=False, excludemax=False,
itertype='iterkeys'):
if not self._data:
return ()
if min is not _marker and min is not None:
min = self._to_key(min)
bucket = self._findbucket(min)
else:
bucket = self._firstbucket
iterargs = min, max, excludemin, excludemax
return _TreeItems(bucket, itertype, iterargs)
def iterkeys(self, min=_marker, max=_marker,
excludemin=False, excludemax=False):
return iter(self.keys(min, max, excludemin, excludemax))
def __iter__(self):
return iter(self.keys())
def minKey(self, min=_marker):
if min is _marker or min is None:
bucket = self._firstbucket
else:
min = self._to_key(min)
bucket = self._findbucket(min)
if bucket is not None:
return bucket.minKey(min)
raise ValueError('empty tree')
def maxKey(self, max=_marker):
data = self._data
if not data:
raise ValueError('empty tree')
if max is _marker or max is None:
return data[-1].child.maxKey()
max = self._to_key(max)
index = self._search(max)
if index and compare(data[index].child.minKey(), max) > 0:
index -= 1 #pragma: no cover no idea how to provoke this
return data[index].child.maxKey(max)
def _set(self, key, value=None, ifunset=False):
if (self._p_jar is not None and
self._p_oid is not None and
self._p_serial is not None):
self._p_jar.readCurrent(self)
data = self._data
if data:
index = self._search(key)
child = data[index].child
else:
index = 0
child = self._bucket_type()
self._firstbucket = child
data.append(_TreeItem(None, child))
result = child._set(key, value, ifunset)
grew = result[0]
if grew:
if type(child) is type(self):
max_size = self.max_internal_size
else:
max_size = self.max_leaf_size
if child.size > max_size:
self._grow(child, index)
# If a BTree contains only a single bucket, BTree.__getstate__()
# includes the bucket's entire state, and the bucket doesn't get
# an oid of its own. So if we have a single oid-less bucket that
# changed, it's *our* oid that should be marked as changed -- the
# bucket doesn't have one.
if (grew is not None and
type(child) is self._bucket_type and
len(data) == 1 and
child._p_oid is None):
self._p_changed = 1
return result
def _grow(self, child, index):
self._p_changed = True
new_child = child._split()
self._data.insert(index+1, _TreeItem(new_child.minKey(), new_child))
if len(self._data) >= self.max_internal_size * 2:
self._split_root()
def _split_root(self):
child = type(self)()
child._data = self._data
child._firstbucket = self._firstbucket
self._data = [_TreeItem(None, child)]
self._grow(child, 0)
def _split(self, index=None):
data = self._data
if index is None:
index = len(data) // 2
next = type(self)()
next._data = data[index:]
first = data[index]
del data[index:]
if len(data) == 0:
self._firstbucket = None # lost our bucket, can't buy no beer
if isinstance(first.child, type(self)):
next._firstbucket = first.child._firstbucket
else:
next._firstbucket = first.child;
return next
def _del(self, key):
if (self._p_jar is not None and
self._p_oid is not None and
self._p_serial is not None):
self._p_jar.readCurrent(self)