FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
cpython/Objects/dictobject.c at doc-link-https · 180909/cpython · GitHub
cpython/Objects/dictobject.c at doc-link-https · 180909/cpython · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
View all industries
View all solutions
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
Accelerator
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
180909
/
cpython
Public
forked from
python/cpython
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
5
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
cpython
/
Objects
/
dictobject.c
Copy path
More file actions
More file actions
Latest commit
History
History
History
5794 lines (5213 loc) · 171 KB
Breadcrumbs
cpython
/
Objects
/
dictobject.c
Copy path
File metadata and controls
5794 lines (5213 loc) · 171 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
/* Dictionary object implementation using a hash table */
/* The distribution includes a separate file, Objects/dictnotes.txt,
describing explorations into dictionary design and optimization.
It covers typical dictionary use patterns, the parameters for
tuning dictionaries, and several ideas for possible optimizations.
*/
/* PyDictKeysObject
This implements the dictionary's hashtable.
As of Python 3.6, this is compact and ordered. Basic idea is described here:
* https://mail.python.org/pipermail/python-dev/2012-December/123028.html
* https://morepypy.blogspot.com/2015/01/faster-more-memory-efficient-and-more.html
layout:
+---------------------+
| dk_refcnt |
| dk_log2_size |
| dk_log2_index_bytes |
| dk_kind |
| dk_usable |
| dk_nentries |
+---------------------+
| dk_indices[] |
| |
+---------------------+
| dk_entries[] |
| |
+---------------------+
dk_indices is actual hashtable. It holds index in entries, or DKIX_EMPTY(-1)
or DKIX_DUMMY(-2).
Size of indices is dk_size. Type of each index in indices is vary on dk_size:
* int8 for dk_size <= 128
* int16 for 256 <= dk_size <= 2**15
* int32 for 2**16 <= dk_size <= 2**31
* int64 for 2**32 <= dk_size
dk_entries is array of PyDictKeyEntry when dk_kind == DICT_KEYS_GENERAL or
PyDictUnicodeEntry otherwise. Its length is USABLE_FRACTION(dk_size).
NOTE: Since negative value is used for DKIX_EMPTY and DKIX_DUMMY, type of
dk_indices entry is signed integer and int16 is used for table which
dk_size == 256.
*/
/*
The DictObject can be in one of two forms.
Either:
A combined table:
ma_values == NULL, dk_refcnt == 1.
Values are stored in the me_value field of the PyDictKeysObject.
Or:
A split table:
ma_values != NULL, dk_refcnt >= 1
Values are stored in the ma_values array.
Only string (unicode) keys are allowed.
There are four kinds of slots in the table (slot is index, and
DK_ENTRIES(keys)[index] if index >= 0):
1. Unused. index == DKIX_EMPTY
Does not hold an active (key, value) pair now and never did. Unused can
transition to Active upon key insertion. This is each slot's initial state.
2. Active. index >= 0, me_key != NULL and me_value != NULL
Holds an active (key, value) pair. Active can transition to Dummy or
Pending upon key deletion (for combined and split tables respectively).
This is the only case in which me_value != NULL.
3. Dummy. index == DKIX_DUMMY (combined only)
Previously held an active (key, value) pair, but that was deleted and an
active pair has not yet overwritten the slot. Dummy can transition to
Active upon key insertion. Dummy slots cannot be made Unused again
else the probe sequence in case of collision would have no way to know
they were once active.
4. Pending. index >= 0, key != NULL, and value == NULL (split only)
Not yet inserted in split-table.
*/
/*
Preserving insertion order
It's simple for combined table. Since dk_entries is mostly append only, we can
get insertion order by just iterating dk_entries.
One exception is .popitem(). It removes last item in dk_entries and decrement
dk_nentries to achieve amortized O(1). Since there are DKIX_DUMMY remains in
dk_indices, we can't increment dk_usable even though dk_nentries is
decremented.
To preserve the order in a split table, a bit vector is used to record the
insertion order. When a key is inserted the bit vector is shifted up by 4 bits
and the index of the key is stored in the low 4 bits.
As a consequence of this, split keys have a maximum size of 16.
*/
/* PyDict_MINSIZE is the starting size for any new dict.
* 8 allows dicts with no more than 5 active entries; experiments suggested
* this suffices for the majority of dicts (consisting mostly of usually-small
* dicts created to pass keyword arguments).
* Making this 8, rather than 4 reduces the number of resizes for most
* dictionaries, without any significant extra memory use.
*/
#define
PyDict_LOG_MINSIZE
3
#define
PyDict_MINSIZE
8
#include
"Python.h"
#include
"pycore_bitutils.h"
// _Py_bit_length
#include
"pycore_call.h"
// _PyObject_CallNoArgs()
#include
"pycore_code.h"
// stats
#include
"pycore_dict.h"
// PyDictKeysObject
#include
"pycore_gc.h"
// _PyObject_GC_IS_TRACKED()
#include
"pycore_object.h"
// _PyObject_GC_TRACK()
#include
"pycore_pyerrors.h"
// _PyErr_Fetch()
#include
"pycore_pystate.h"
// _PyThreadState_GET()
#include
"stringlib/eq.h"
// unicode_eq()
#include
<stdbool.h>
/*[clinic input]
class dict "PyDictObject *" "&PyDict_Type"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=f157a5a0ce9589d6]*/
/*
To ensure the lookup algorithm terminates, there must be at least one Unused
slot (NULL key) in the table.
To avoid slowing down lookups on a near-full table, we resize the table when
it's USABLE_FRACTION (currently two-thirds) full.
*/
#define
PERTURB_SHIFT
5
/*
Major subtleties ahead: Most hash schemes depend on having a "good" hash
function, in the sense of simulating randomness. Python doesn't: its most
important hash functions (for ints) are very regular in common
cases:
>>>[hash(i) for i in range(4)]
[0, 1, 2, 3]
This isn't necessarily bad! To the contrary, in a table of size 2**i, taking
the low-order i bits as the initial table index is extremely fast, and there
are no collisions at all for dicts indexed by a contiguous range of ints. So
this gives better-than-random behavior in common cases, and that's very
desirable.
OTOH, when collisions occur, the tendency to fill contiguous slices of the
hash table makes a good collision resolution strategy crucial. Taking only
the last i bits of the hash code is also vulnerable: for example, consider
the list [i << 16 for i in range(20000)] as a set of keys. Since ints are
their own hash codes, and this fits in a dict of size 2**15, the last 15 bits
of every hash code are all 0: they *all* map to the same table index.
But catering to unusual cases should not slow the usual ones, so we just take
the last i bits anyway. It's up to collision resolution to do the rest. If
we *usually* find the key we're looking for on the first try (and, it turns
out, we usually do -- the table load factor is kept under 2/3, so the odds
are solidly in our favor), then it makes best sense to keep the initial index
computation dirt cheap.
The first half of collision resolution is to visit table indices via this
recurrence:
j = ((5*j) + 1) mod 2**i
For any initial j in range(2**i), repeating that 2**i times generates each
int in range(2**i) exactly once (see any text on random-number generation for
proof). By itself, this doesn't help much: like linear probing (setting
j += 1, or j -= 1, on each loop trip), it scans the table entries in a fixed
order. This would be bad, except that's not the only thing we do, and it's
actually *good* in the common cases where hash keys are consecutive. In an
example that's really too small to make this entirely clear, for a table of
size 2**3 the order of indices is:
0 -> 1 -> 6 -> 7 -> 4 -> 5 -> 2 -> 3 -> 0 [and here it's repeating]
If two things come in at index 5, the first place we look after is index 2,
not 6, so if another comes in at index 6 the collision at 5 didn't hurt it.
Linear probing is deadly in this case because there the fixed probe order
is the *same* as the order consecutive keys are likely to arrive. But it's
extremely unlikely hash codes will follow a 5*j+1 recurrence by accident,
and certain that consecutive hash codes do not.
The other half of the strategy is to get the other bits of the hash code
into play. This is done by initializing a (unsigned) vrbl "perturb" to the
full hash code, and changing the recurrence to:
perturb >>= PERTURB_SHIFT;
j = (5*j) + 1 + perturb;
use j % 2**i as the next table index;
Now the probe sequence depends (eventually) on every bit in the hash code,
and the pseudo-scrambling property of recurring on 5*j+1 is more valuable,
because it quickly magnifies small differences in the bits that didn't affect
the initial index. Note that because perturb is unsigned, if the recurrence
is executed often enough perturb eventually becomes and remains 0. At that
point (very rarely reached) the recurrence is on (just) 5*j+1 again, and
that's certain to find an empty slot eventually (since it generates every int
in range(2**i), and we make sure there's always at least one empty slot).
Selecting a good value for PERTURB_SHIFT is a balancing act. You want it
small so that the high bits of the hash code continue to affect the probe
sequence across iterations; but you want it large so that in really bad cases
the high-order hash bits have an effect on early iterations. 5 was "the
best" in minimizing total collisions across experiments Tim Peters ran (on
both normal and pathological cases), but 4 and 6 weren't significantly worse.
Historical: Reimer Behrends contributed the idea of using a polynomial-based
approach, using repeated multiplication by x in GF(2**n) where an irreducible
polynomial for each table size was chosen such that x was a primitive root.
Christian Tismer later extended that to use division by x instead, as an
efficient way to get the high bits of the hash code into play. This scheme
also gave excellent collision statistics, but was more expensive: two
if-tests were required inside the loop; computing "the next" index took about
the same number of operations but without as much potential parallelism
(e.g., computing 5*j can go on at the same time as computing 1+perturb in the
above, and then shifting perturb can be done while the table index is being
masked); and the PyDictObject struct required a member to hold the table's
polynomial. In Tim's experiments the current scheme ran faster, produced
equally good collision statistics, needed less code & used less memory.
*/
static
int
dictresize
(
PyDictObject
*
mp
,
uint8_t
log_newsize
,
int
unicode
);
static
PyObject
*
dict_iter
(
PyDictObject
*
dict
);
/*Global counter used to set ma_version_tag field of dictionary.
* It is incremented each time that a dictionary is created and each
* time that a dictionary is modified. */
uint64_t
_pydict_global_version
=
0
;
#include
"clinic/dictobject.c.h"
#if
PyDict_MAXFREELIST
>
0
static
struct
_Py_dict_state
*
get_dict_state
(
void
)
{
PyInterpreterState
*
interp
=
_PyInterpreterState_GET
();
return
&
interp
->
dict_state
;
}
#endif
void
_PyDict_ClearFreeList
(
PyInterpreterState
*
interp
)
{
#if
PyDict_MAXFREELIST
>
0
struct
_Py_dict_state
*
state
=
&
interp
->
dict_state
;
while
(
state
->
numfree
) {
PyDictObject
*
op
=
state
->
free_list
[
--
state
->
numfree
];
assert
(
PyDict_CheckExact
(
op
));
PyObject_GC_Del
(
op
);
}
while
(
state
->
keys_numfree
) {
PyObject_Free
(
state
->
keys_free_list
[
--
state
->
keys_numfree
]);
}
#endif
}
void
_PyDict_Fini
(
PyInterpreterState
*
interp
)
{
_PyDict_ClearFreeList
(
interp
);
#if
defined(
Py_DEBUG
)
&&
PyDict_MAXFREELIST
>
0
struct
_Py_dict_state
*
state
=
&
interp
->
dict_state
;
state
->
numfree
=
-1
;
state
->
keys_numfree
=
-1
;
#endif
}
static
inline
Py_hash_t
unicode_get_hash
(
PyObject
*
o
)
{
assert
(
PyUnicode_CheckExact
(
o
));
return
_PyASCIIObject_CAST
(
o
)
->
hash
;
}
/* Print summary info about the state of the optimized allocator */
void
_PyDict_DebugMallocStats
(
FILE
*
out
)
{
#if
PyDict_MAXFREELIST
>
0
struct
_Py_dict_state
*
state
=
get_dict_state
();
_PyDebugAllocatorStats
(
out
,
"free PyDictObject"
,
state
->
numfree
,
sizeof
(
PyDictObject
));
#endif
}
#define
DK_MASK
(
dk
) (DK_SIZE(dk)-1)
static
void
free_keys_object
(
PyDictKeysObject
*
keys
);
static
inline
void
dictkeys_incref
(
PyDictKeysObject
*
dk
)
{
#ifdef
Py_REF_DEBUG
_Py_RefTotal
++
;
#endif
dk
->
dk_refcnt
++
;
}
static
inline
void
dictkeys_decref
(
PyDictKeysObject
*
dk
)
{
assert
(
dk
->
dk_refcnt
>
0
);
#ifdef
Py_REF_DEBUG
_Py_RefTotal
--
;
#endif
if
(
--
dk
->
dk_refcnt
==
0
) {
free_keys_object
(
dk
);
}
}
/* lookup indices. returns DKIX_EMPTY, DKIX_DUMMY, or ix >=0 */
static
inline
Py_ssize_t
dictkeys_get_index
(
const
PyDictKeysObject
*
keys
,
Py_ssize_t
i
)
{
int
log2size
=
DK_LOG_SIZE
(
keys
);
Py_ssize_t
ix
;
if
(
log2size
<
8
) {
const
int8_t
*
indices
=
(
const
int8_t
*
)(
keys
->
dk_indices
);
ix
=
indices
[
i
];
}
else
if
(
log2size
<
16
) {
const
int16_t
*
indices
=
(
const
int16_t
*
)(
keys
->
dk_indices
);
ix
=
indices
[
i
];
}
#if
SIZEOF_VOID_P
>
4
else
if
(
log2size
>=
32
) {
const
int64_t
*
indices
=
(
const
int64_t
*
)(
keys
->
dk_indices
);
ix
=
indices
[
i
];
}
#endif
else
{
const
int32_t
*
indices
=
(
const
int32_t
*
)(
keys
->
dk_indices
);
ix
=
indices
[
i
];
}
assert
(
ix
>=
DKIX_DUMMY
);
return
ix
;
}
/* write to indices. */
static
inline
void
dictkeys_set_index
(
PyDictKeysObject
*
keys
,
Py_ssize_t
i
,
Py_ssize_t
ix
)
{
int
log2size
=
DK_LOG_SIZE
(
keys
);
assert
(
ix
>=
DKIX_DUMMY
);
assert
(
keys
->
dk_version
==
0
);
if
(
log2size
<
8
) {
int8_t
*
indices
=
(
int8_t
*
)(
keys
->
dk_indices
);
assert
(
ix
<=
0x7f
);
indices
[
i
]
=
(
char
)
ix
;
}
else
if
(
log2size
<
16
) {
int16_t
*
indices
=
(
int16_t
*
)(
keys
->
dk_indices
);
assert
(
ix
<=
0x7fff
);
indices
[
i
]
=
(
int16_t
)
ix
;
}
#if
SIZEOF_VOID_P
>
4
else
if
(
log2size
>=
32
) {
int64_t
*
indices
=
(
int64_t
*
)(
keys
->
dk_indices
);
indices
[
i
]
=
ix
;
}
#endif
else
{
int32_t
*
indices
=
(
int32_t
*
)(
keys
->
dk_indices
);
assert
(
ix
<=
0x7fffffff
);
indices
[
i
]
=
(
int32_t
)
ix
;
}
}
/* USABLE_FRACTION is the maximum dictionary load.
* Increasing this ratio makes dictionaries more dense resulting in more
* collisions. Decreasing it improves sparseness at the expense of spreading
* indices over more cache lines and at the cost of total memory consumed.
*
* USABLE_FRACTION must obey the following:
* (0 < USABLE_FRACTION(n) < n) for all n >= 2
*
* USABLE_FRACTION should be quick to calculate.
* Fractions around 1/2 to 2/3 seem to work well in practice.
*/
#define
USABLE_FRACTION
(
n
) (((n) << 1)/3)
/* Find the smallest dk_size >= minsize. */
static
inline
uint8_t
calculate_log2_keysize
(
Py_ssize_t
minsize
)
{
#if
SIZEOF_LONG
==
SIZEOF_SIZE_T
minsize
=
(
minsize
|
PyDict_MINSIZE
)
-
1
;
return
_Py_bit_length
(
minsize
| (
PyDict_MINSIZE
-
1
));
#elif
defined(
_MSC_VER
)
// On 64bit Windows, sizeof(long) == 4.
minsize
=
(
minsize
|
PyDict_MINSIZE
)
-
1
;
unsigned long
msb
;
_BitScanReverse64
(
&
msb
, (
uint64_t
)
minsize
);
return
(
uint8_t
)(
msb
+
1
);
#else
uint8_t
log2_size
;
for
(
log2_size
=
PyDict_LOG_MINSIZE
;
(((
Py_ssize_t
)
1
) <<
log2_size
)
<
minsize
;
log2_size
++
)
;
return
log2_size
;
#endif
}
/* estimate_keysize is reverse function of USABLE_FRACTION.
*
* This can be used to reserve enough size to insert n entries without
* resizing.
*/
static
inline
uint8_t
estimate_log2_keysize
(
Py_ssize_t
n
)
{
return
calculate_log2_keysize
((
n
*
3
+
1
) /
2
);
}
/* GROWTH_RATE. Growth rate upon hitting maximum load.
* Currently set to used*3.
* This means that dicts double in size when growing without deletions,
* but have more head room when the number of deletions is on a par with the
* number of insertions. See also bpo-17563 and bpo-33205.
*
* GROWTH_RATE was set to used*4 up to version 3.2.
* GROWTH_RATE was set to used*2 in version 3.3.0
* GROWTH_RATE was set to used*2 + capacity/2 in 3.4.0-3.6.0.
*/
#define
GROWTH_RATE
(
d
) ((d)->ma_used*3)
/* This immutable, empty PyDictKeysObject is used for PyDict_Clear()
* (which cannot fail and thus can do no allocation).
*/
static
PyDictKeysObject
empty_keys_struct
=
{
1
,
/* dk_refcnt */
0
,
/* dk_log2_size */
0
,
/* dk_log2_index_bytes */
DICT_KEYS_UNICODE
,
/* dk_kind */
1
,
/* dk_version */
0
,
/* dk_usable (immutable) */
0
,
/* dk_nentries */
{
DKIX_EMPTY
,
DKIX_EMPTY
,
DKIX_EMPTY
,
DKIX_EMPTY
,
DKIX_EMPTY
,
DKIX_EMPTY
,
DKIX_EMPTY
,
DKIX_EMPTY
},
/* dk_indices */
};
#define
Py_EMPTY_KEYS
&empty_keys_struct
/* Uncomment to check the dict content in _PyDict_CheckConsistency() */
// #define DEBUG_PYDICT
#ifdef
DEBUG_PYDICT
# define
ASSERT_CONSISTENT
(
op
) assert(_PyDict_CheckConsistency((PyObject *)(op), 1))
#else
# define
ASSERT_CONSISTENT
(
op
) assert(_PyDict_CheckConsistency((PyObject *)(op), 0))
#endif
static
inline
int
get_index_from_order
(
PyDictObject
*
mp
,
Py_ssize_t
i
)
{
assert
(
mp
->
ma_used
<=
SHARED_KEYS_MAX_SIZE
);
assert
(
i
<
(((
char
*
)
mp
->
ma_values
)[
-2
]));
return
((
char
*
)
mp
->
ma_values
)[
-3
-
i
];
}
#ifdef
DEBUG_PYDICT
static
void
dump_entries
(
PyDictKeysObject
*
dk
)
{
for
(
Py_ssize_t
i
=
0
;
i
<
dk
->
dk_nentries
;
i
++
) {
if
(
DK_IS_UNICODE
(
dk
)) {
PyDictUnicodeEntry
*
ep
=
&
DK_UNICODE_ENTRIES
(
dk
)[
i
];
printf
(
"key=%p value=%p\n"
,
ep
->
me_key
,
ep
->
me_value
);
}
else
{
PyDictKeyEntry
*
ep
=
&
DK_ENTRIES
(
dk
)[
i
];
printf
(
"key=%p hash=%lx value=%p\n"
,
ep
->
me_key
,
ep
->
me_hash
,
ep
->
me_value
);
}
}
}
#endif
int
_PyDict_CheckConsistency
(
PyObject
*
op
,
int
check_content
)
{
#define
CHECK
(
expr
) \
do { if (!(expr)) { _PyObject_ASSERT_FAILED_MSG(op, Py_STRINGIFY(expr)); } } while (0)
assert
(
op
!=
NULL
);
CHECK
(
PyDict_Check
(
op
));
PyDictObject
*
mp
=
(
PyDictObject
*
)
op
;
PyDictKeysObject
*
keys
=
mp
->
ma_keys
;
int
splitted
=
_PyDict_HasSplitTable
(
mp
);
Py_ssize_t
usable
=
USABLE_FRACTION
(
DK_SIZE
(
keys
));
CHECK
(
0
<=
mp
->
ma_used
&&
mp
->
ma_used
<=
usable
);
CHECK
(
0
<=
keys
->
dk_usable
&&
keys
->
dk_usable
<=
usable
);
CHECK
(
0
<=
keys
->
dk_nentries
&&
keys
->
dk_nentries
<=
usable
);
CHECK
(
keys
->
dk_usable
+
keys
->
dk_nentries
<=
usable
);
if
(!
splitted
) {
/* combined table */
CHECK
(
keys
->
dk_kind
!=
DICT_KEYS_SPLIT
);
CHECK
(
keys
->
dk_refcnt
==
1
||
keys
==
Py_EMPTY_KEYS
);
}
else
{
CHECK
(
keys
->
dk_kind
==
DICT_KEYS_SPLIT
);
CHECK
(
mp
->
ma_used
<=
SHARED_KEYS_MAX_SIZE
);
}
if
(
check_content
) {
for
(
Py_ssize_t
i
=
0
;
i
<
DK_SIZE
(
keys
);
i
++
) {
Py_ssize_t
ix
=
dictkeys_get_index
(
keys
,
i
);
CHECK
(
DKIX_DUMMY
<=
ix
&&
ix
<=
usable
);
}
if
(
keys
->
dk_kind
==
DICT_KEYS_GENERAL
) {
PyDictKeyEntry
*
entries
=
DK_ENTRIES
(
keys
);
for
(
Py_ssize_t
i
=
0
;
i
<
usable
;
i
++
) {
PyDictKeyEntry
*
entry
=
&
entries
[
i
];
PyObject
*
key
=
entry
->
me_key
;
if
(
key
!=
NULL
) {
/* test_dict fails if PyObject_Hash() is called again */
CHECK
(
entry
->
me_hash
!=
-1
);
CHECK
(
entry
->
me_value
!=
NULL
);
if
(
PyUnicode_CheckExact
(
key
)) {
Py_hash_t
hash
=
unicode_get_hash
(
key
);
CHECK
(
entry
->
me_hash
==
hash
);
}
}
}
}
else
{
PyDictUnicodeEntry
*
entries
=
DK_UNICODE_ENTRIES
(
keys
);
for
(
Py_ssize_t
i
=
0
;
i
<
usable
;
i
++
) {
PyDictUnicodeEntry
*
entry
=
&
entries
[
i
];
PyObject
*
key
=
entry
->
me_key
;
if
(
key
!=
NULL
) {
CHECK
(
PyUnicode_CheckExact
(
key
));
Py_hash_t
hash
=
unicode_get_hash
(
key
);
CHECK
(
hash
!=
-1
);
if
(!
splitted
) {
CHECK
(
entry
->
me_value
!=
NULL
);
}
}
if
(
splitted
) {
CHECK
(
entry
->
me_value
==
NULL
);
}
}
}
if
(
splitted
) {
CHECK
(
mp
->
ma_used
<=
SHARED_KEYS_MAX_SIZE
);
/* splitted table */
int
duplicate_check
=
0
;
for
(
Py_ssize_t
i
=
0
;
i
<
mp
->
ma_used
;
i
++
) {
int
index
=
get_index_from_order
(
mp
,
i
);
CHECK
((
duplicate_check
&
(
1
<<
index
))
==
0
);
duplicate_check
|= (
1
<<
index
);
CHECK
(
mp
->
ma_values
->
values
[
index
]
!=
NULL
);
}
}
}
return
1
;
#undef
CHECK
}
static
PyDictKeysObject
*
new_keys_object
(
uint8_t
log2_size
,
bool
unicode
)
{
PyDictKeysObject
*
dk
;
Py_ssize_t
usable
;
int
log2_bytes
;
size_t
entry_size
=
unicode
?
sizeof
(
PyDictUnicodeEntry
) :
sizeof
(
PyDictKeyEntry
);
assert
(
log2_size
>=
PyDict_LOG_MINSIZE
);
usable
=
USABLE_FRACTION
(
1
<<
log2_size
);
if
(
log2_size
<
8
) {
log2_bytes
=
log2_size
;
}
else
if
(
log2_size
<
16
) {
log2_bytes
=
log2_size
+
1
;
}
#if
SIZEOF_VOID_P
>
4
else
if
(
log2_size
>=
32
) {
log2_bytes
=
log2_size
+
3
;
}
#endif
else
{
log2_bytes
=
log2_size
+
2
;
}
#if
PyDict_MAXFREELIST
>
0
struct
_Py_dict_state
*
state
=
get_dict_state
();
#ifdef
Py_DEBUG
// new_keys_object() must not be called after _PyDict_Fini()
assert
(
state
->
keys_numfree
!=
-1
);
#endif
if
(
log2_size
==
PyDict_LOG_MINSIZE
&&
unicode
&&
state
->
keys_numfree
>
0
) {
dk
=
state
->
keys_free_list
[
--
state
->
keys_numfree
];
OBJECT_STAT_INC
(
from_freelist
);
}
else
#endif
{
dk
=
PyObject_Malloc
(
sizeof
(
PyDictKeysObject
)
+
((
size_t
)
1
<<
log2_bytes
)
+
entry_size
*
usable
);
if
(
dk
==
NULL
) {
PyErr_NoMemory
();
return
NULL
;
}
}
#ifdef
Py_REF_DEBUG
_Py_RefTotal
++
;
#endif
dk
->
dk_refcnt
=
1
;
dk
->
dk_log2_size
=
log2_size
;
dk
->
dk_log2_index_bytes
=
log2_bytes
;
dk
->
dk_kind
=
unicode
?
DICT_KEYS_UNICODE
:
DICT_KEYS_GENERAL
;
dk
->
dk_nentries
=
0
;
dk
->
dk_usable
=
usable
;
dk
->
dk_version
=
0
;
memset
(
&
dk
->
dk_indices
[
0
],
0xff
, ((
size_t
)
1
<<
log2_bytes
));
memset
(
&
dk
->
dk_indices
[(
size_t
)
1
<<
log2_bytes
],
0
,
entry_size
*
usable
);
return
dk
;
}
static
void
free_keys_object
(
PyDictKeysObject
*
keys
)
{
assert
(
keys
!=
Py_EMPTY_KEYS
);
if
(
DK_IS_UNICODE
(
keys
)) {
PyDictUnicodeEntry
*
entries
=
DK_UNICODE_ENTRIES
(
keys
);
Py_ssize_t
i
,
n
;
for
(
i
=
0
,
n
=
keys
->
dk_nentries
;
i
<
n
;
i
++
) {
Py_XDECREF
(
entries
[
i
].
me_key
);
Py_XDECREF
(
entries
[
i
].
me_value
);
}
}
else
{
PyDictKeyEntry
*
entries
=
DK_ENTRIES
(
keys
);
Py_ssize_t
i
,
n
;
for
(
i
=
0
,
n
=
keys
->
dk_nentries
;
i
<
n
;
i
++
) {
Py_XDECREF
(
entries
[
i
].
me_key
);
Py_XDECREF
(
entries
[
i
].
me_value
);
}
}
#if
PyDict_MAXFREELIST
>
0
struct
_Py_dict_state
*
state
=
get_dict_state
();
#ifdef
Py_DEBUG
// free_keys_object() must not be called after _PyDict_Fini()
assert
(
state
->
keys_numfree
!=
-1
);
#endif
if
(
DK_LOG_SIZE
(
keys
)
==
PyDict_LOG_MINSIZE
&&
state
->
keys_numfree
<
PyDict_MAXFREELIST
&&
DK_IS_UNICODE
(
keys
)) {
state
->
keys_free_list
[
state
->
keys_numfree
++
]
=
keys
;
OBJECT_STAT_INC
(
to_freelist
);
return
;
}
#endif
PyObject_Free
(
keys
);
}
static
inline
PyDictValues
*
new_values
(
Py_ssize_t
size
)
{
assert
(
size
>
0
);
size_t
prefix_size
=
_Py_SIZE_ROUND_UP
(
size
+
2
,
sizeof
(
PyObject
*
));
assert
(
prefix_size
<
256
);
size_t
n
=
prefix_size
+
size
*
sizeof
(
PyObject
*
);
uint8_t
*
mem
=
PyMem_Malloc
(
n
);
if
(
mem
==
NULL
) {
return
NULL
;
}
assert
(
prefix_size
%
sizeof
(
PyObject
*
)
==
0
);
mem
[
prefix_size
-
1
]
=
(
uint8_t
)
prefix_size
;
return
(
PyDictValues
*
)(
mem
+
prefix_size
);
}
static
inline
void
free_values
(
PyDictValues
*
values
)
{
int
prefix_size
=
((
uint8_t
*
)
values
)[
-1
];
PyMem_Free
(((
char
*
)
values
)
-
prefix_size
);
}
/* Consumes a reference to the keys object */
static
PyObject
*
new_dict
(
PyDictKeysObject
*
keys
,
PyDictValues
*
values
,
Py_ssize_t
used
,
int
free_values_on_failure
)
{
PyDictObject
*
mp
;
assert
(
keys
!=
NULL
);
#if
PyDict_MAXFREELIST
>
0
struct
_Py_dict_state
*
state
=
get_dict_state
();
#ifdef
Py_DEBUG
// new_dict() must not be called after _PyDict_Fini()
assert
(
state
->
numfree
!=
-1
);
#endif
if
(
state
->
numfree
) {
mp
=
state
->
free_list
[
--
state
->
numfree
];
assert
(
mp
!=
NULL
);
assert
(
Py_IS_TYPE
(
mp
,
&
PyDict_Type
));
OBJECT_STAT_INC
(
from_freelist
);
_Py_NewReference
((
PyObject
*
)
mp
);
}
else
#endif
{
mp
=
PyObject_GC_New
(
PyDictObject
,
&
PyDict_Type
);
if
(
mp
==
NULL
) {
dictkeys_decref
(
keys
);
if
(
free_values_on_failure
) {
free_values
(
values
);
}
return
NULL
;
}
}
mp
->
ma_keys
=
keys
;
mp
->
ma_values
=
values
;
mp
->
ma_used
=
used
;
mp
->
ma_version_tag
=
DICT_NEXT_VERSION
();
ASSERT_CONSISTENT
(
mp
);
return
(
PyObject
*
)
mp
;
}
static
inline
Py_ssize_t
shared_keys_usable_size
(
PyDictKeysObject
*
keys
)
{
return
keys
->
dk_nentries
+
keys
->
dk_usable
;
}
/* Consumes a reference to the keys object */
static
PyObject
*
new_dict_with_shared_keys
(
PyDictKeysObject
*
keys
)
{
PyDictValues
*
values
;
Py_ssize_t
i
,
size
;
size
=
shared_keys_usable_size
(
keys
);
values
=
new_values
(
size
);
if
(
values
==
NULL
) {
dictkeys_decref
(
keys
);
return
PyErr_NoMemory
();
}
((
char
*
)
values
)[
-2
]
=
0
;
for
(
i
=
0
;
i
<
size
;
i
++
) {
values
->
values
[
i
]
=
NULL
;
}
return
new_dict
(
keys
,
values
,
0
,
1
);
}
static
PyDictKeysObject
*
clone_combined_dict_keys
(
PyDictObject
*
orig
)
{
assert
(
PyDict_Check
(
orig
));
assert
(
Py_TYPE
(
orig
)
->
tp_iter
==
(
getiterfunc
)
dict_iter
);
assert
(
orig
->
ma_values
==
NULL
);
assert
(
orig
->
ma_keys
->
dk_refcnt
==
1
);
Py_ssize_t
keys_size
=
_PyDict_KeysSize
(
orig
->
ma_keys
);
PyDictKeysObject
*
keys
=
PyObject_Malloc
(
keys_size
);
if
(
keys
==
NULL
) {
PyErr_NoMemory
();
return
NULL
;
}
memcpy
(
keys
,
orig
->
ma_keys
,
keys_size
);
/* After copying key/value pairs, we need to incref all
keys and values and they are about to be co-owned by a
new dict object. */
PyObject
*
*
pkey
,
*
*
pvalue
;
size_t
offs
;
if
(
DK_IS_UNICODE
(
orig
->
ma_keys
)) {
PyDictUnicodeEntry
*
ep0
=
DK_UNICODE_ENTRIES
(
keys
);
pkey
=
&
ep0
->
me_key
;
pvalue
=
&
ep0
->
me_value
;
offs
=
sizeof
(
PyDictUnicodeEntry
) /
sizeof
(
PyObject
*
);
}
else
{
PyDictKeyEntry
*
ep0
=
DK_ENTRIES
(
keys
);
pkey
=
&
ep0
->
me_key
;
pvalue
=
&
ep0
->
me_value
;
offs
=
sizeof
(
PyDictKeyEntry
) /
sizeof
(
PyObject
*
);
}
Py_ssize_t
n
=
keys
->
dk_nentries
;
for
(
Py_ssize_t
i
=
0
;
i
<
n
;
i
++
) {
PyObject
*
value
=
*
pvalue
;
if
(
value
!=
NULL
) {
Py_INCREF
(
value
);
Py_INCREF
(
*
pkey
);
}
pvalue
+=
offs
;
pkey
+=
offs
;
}
/* Since we copied the keys table we now have an extra reference
in the system. Manually call increment _Py_RefTotal to signal that
we have it now; calling dictkeys_incref would be an error as
keys->dk_refcnt is already set to 1 (after memcpy). */
#ifdef
Py_REF_DEBUG
_Py_RefTotal
++
;
#endif
return
keys
;
}
PyObject
*
PyDict_New
(
void
)
{
dictkeys_incref
(
Py_EMPTY_KEYS
);
return
new_dict
(
Py_EMPTY_KEYS
,
NULL
,
0
,
0
);
}
/* Search index of hash table from offset of entry table */
static
Py_ssize_t
lookdict_index
(
PyDictKeysObject
*
k
,
Py_hash_t
hash
,
Py_ssize_t
index
)
{
size_t
mask
=
DK_MASK
(
k
);
size_t
perturb
=
(
size_t
)
hash
;
size_t
i
=
(
size_t
)
hash
&
mask
;
for
(;;) {
Py_ssize_t
ix
=
dictkeys_get_index
(
k
,
i
);
if
(
ix
==
index
) {
return
i
;
}
if
(
ix
==
DKIX_EMPTY
) {
return
DKIX_EMPTY
;
}
perturb
>>=
PERTURB_SHIFT
;
i
=
mask
&
(
i
*
5
+
perturb
+
1
);
}
Py_UNREACHABLE
();
}
// Search non-Unicode key from Unicode table
static
Py_ssize_t
unicodekeys_lookup_generic
(
PyDictObject
*
mp
,
PyDictKeysObject
*
dk
,
PyObject
*
key
,
Py_hash_t
hash
)
{
PyDictUnicodeEntry
*
ep0
=
DK_UNICODE_ENTRIES
(
dk
);
size_t
mask
=
DK_MASK
(
dk
);
size_t
perturb
=
hash
;
size_t
i
=
(
size_t
)
hash
&
mask
;
Py_ssize_t
ix
;
for
(;;) {
ix
=
dictkeys_get_index
(
dk
,
i
);
if
(
ix
>=
0
) {
PyDictUnicodeEntry
*
ep
=
&
ep0
[
ix
];
assert
(
ep
->
me_key
!=
NULL
);
assert
(
PyUnicode_CheckExact
(
ep
->
me_key
));
if
(
ep
->
me_key
==
key
) {
return
ix
;
}
if
(
unicode_get_hash
(
ep
->
me_key
)
==
hash
) {
PyObject
*
startkey
=
ep
->
me_key
;
Py_INCREF
(
startkey
);
int
cmp
=
PyObject_RichCompareBool
(
startkey
,
key
,
Py_EQ
);
Py_DECREF
(
startkey
);
if
(
cmp
<
0
) {
return
DKIX_ERROR
;
}
if
(
dk
==
mp
->
ma_keys
&&
ep
->
me_key
==
startkey
) {
if
(
cmp
>
0
) {
return
ix
;
}
}
else
{
/* The dict was mutated, restart */
return
DKIX_KEY_CHANGED
;
}
}
}
else
if
(
ix
==
DKIX_EMPTY
) {
return
DKIX_EMPTY
;
}
perturb
>>=
PERTURB_SHIFT
;
i
=
mask
&
(
i
*
5
+
perturb
+
1
);
}
Py_UNREACHABLE
();
}
// Search Unicode key from Unicode table.
static
Py_ssize_t
_Py_HOT_FUNCTION
unicodekeys_lookup_unicode
(
PyDictKeysObject
*
dk
,
PyObject
*
key
,
Py_hash_t
hash
)
{
PyDictUnicodeEntry
*
ep0
=
DK_UNICODE_ENTRIES
(
dk
);
size_t
mask
=
DK_MASK
(
dk
);
size_t
perturb
=
hash
;
size_t
i
=
(
size_t
)
hash
&
mask
;
Py_ssize_t
ix
;
for
(;;) {
ix
=
dictkeys_get_index
(
dk
,
i
);
if
(
ix
>=
0
) {
PyDictUnicodeEntry
*
ep
=
&
ep0
[
ix
];
assert
(
ep
->
me_key
!=
NULL
);
assert
(
PyUnicode_CheckExact
(
ep
->
me_key
));
if
(
ep
->
me_key
==
key
||
(
unicode_get_hash
(
ep
->
me_key
)
==
hash
&&
unicode_eq
(
ep
->
me_key
,
key
))) {
return
ix
;
}
}
else
if
(
ix
==
DKIX_EMPTY
) {
return
DKIX_EMPTY
;
}
perturb
>>=
PERTURB_SHIFT
;
i
=
mask
&
(
i
*
5
+
perturb
+
1
);
ix
=
dictkeys_get_index
(
dk
,
i
);
if
(
ix
>=
0
) {
PyDictUnicodeEntry
*
ep
=
&
ep0
[
ix
];
assert
(
ep
->
me_key
!=
NULL
);
assert
(
PyUnicode_CheckExact
(
ep
->
me_key
));
if
(
ep
->
me_key
==
key
||
(
unicode_get_hash
(
ep
->
me_key
)
==
hash
&&
unicode_eq
(
ep
->
me_key
,
key
))) {
return
ix
;
}
}
else
if
(
ix
==
DKIX_EMPTY
) {
return
DKIX_EMPTY
;
}
perturb
>>=
PERTURB_SHIFT
;
i
=
mask
&
(
i
*
5
+
perturb
+
1
);
}
Py_UNREACHABLE
();
}
// Search key from Generic table.
static
Py_ssize_t
dictkeys_generic_lookup
(
PyDictObject
*
mp
,
PyDictKeysObject
*
dk
,
PyObject
*
key
,
Py_hash_t
hash
)
{
PyDictKeyEntry
*
ep0
=
DK_ENTRIES
(
dk
);
size_t
mask
=
DK_MASK
(
dk
);
size_t
perturb
=
hash
;
size_t
i
=
(
size_t
)
hash
&
mask
;
Py_ssize_t
ix
;
for
(;;) {
ix
=
dictkeys_get_index
(
dk
,
i
);
if
(
ix
>=
0
) {
PyDictKeyEntry
*
ep
=
&
ep0
[
ix
];
assert
(
ep
->
me_key
!=
NULL
);
if
(
ep
->
me_key
==
key
) {
return
ix
;
}
if
(
ep
->
me_hash
==
hash
) {
PyObject
*
startkey
=
ep
->
me_key
;
Py_INCREF
(
startkey
);
int
cmp
=
PyObject_RichCompareBool
(
startkey
,
key
,
Py_EQ
);
Py_DECREF
(
startkey
);
if
(
cmp
<
0
) {
return
DKIX_ERROR
;
}
if
(
dk
==
mp
->
ma_keys
&&
ep
->
me_key
==
startkey
) {
if
(
cmp
>
0
) {
return
ix
;
}
}
else
{
/* The dict was mutated, restart */
return
DKIX_KEY_CHANGED
;
}
}
}
else
if
(
ix
==
DKIX_EMPTY
) {
return
DKIX_EMPTY
;
}
perturb
>>=
PERTURB_SHIFT
;
i
=
mask
&
(
i
*
5
+
perturb
+
1
);
}
Py_UNREACHABLE
();
}
View remainder of file in raw view
Footer
© 2026 GitHub, Inc.
Footer navigation
Terms
Privacy
Security
Status
Community
Docs
Contact
You can’t perform that action at this time.
Back
|
FazBrowse Home
|
New Git URL