Debian Codegraph @

rpython/memory/lldict.py

raw symbols SCIP
1 from rpython.rtyper.lltypesystem import lltype, llmemory
2 from rpython.rtyper.lltypesystem import rdict
3 from rpython.rlib.objectmodel import we_are_translated
4 from rpython.memory.support import mangle_hash
5
6 # This is a low-level AddressDict, reusing a lot of the logic from rdict.py.
7 # xxx this is very dependent on the details of rdict.py
8
9 alloc_count = 0 # for debugging
10
11 def count_alloc(delta):
12 "NOT_RPYTHON"
13 global alloc_count
14 alloc_count += delta
15
16
17 def newdict(length_estimate=0):
18 return rdict.ll_newdict_size(DICT, length_estimate)
19
20 def dict_allocate():
21 if not we_are_translated(): count_alloc(+1)
22 return lltype.malloc(DICT, flavor="raw")
23
24 def dict_delete(d):
25 dict_delete_entries(d.entries)
26 lltype.free(d, flavor="raw")
27 if not we_are_translated(): count_alloc(-1)
28
29 def dict_allocate_entries(n):
30 if not we_are_translated(): count_alloc(+1)
31 # 'raw zero varsize malloc with length field' is not really implemented.
32 # we can initialize the memory to zero manually
33 entries = lltype.malloc(ENTRIES, n, flavor="raw")
34 i = 0
35 while i < n:
36 entries[i].key = llmemory.NULL
37 i += 1
38 return entries
39
40 def dict_delete_entries(entries):
41 lltype.free(entries, flavor="raw")
42 if not we_are_translated(): count_alloc(-1)
43
44 def _hash(adr):
45 return mangle_hash(llmemory.cast_adr_to_int(adr))
46
47 def dict_keyhash(d, key):
48 return _hash(key)
49
50 def dict_entry_valid(entries, i):
51 return entries[i].key != llmemory.NULL
52
53 def dict_entry_hash(entries, i):
54 return _hash(entries[i].key)
55
56 def dict_get(d, key, default=llmemory.NULL):
57 return rdict.ll_get(d, key, default)
58
59 def dict_add(d, key):
60 rdict.ll_dict_setitem(d, key, llmemory.NULL)
61
62 def dict_insertclean(d, key, value):
63 rdict.ll_dict_insertclean(d, key, value, _hash(key))
64
65 def dict_foreach(d, callback, arg):
66 entries = d.entries
67 i = len(entries) - 1
68 while i >= 0:
69 if dict_entry_valid(entries, i):
70 callback(entries[i].key, entries[i].value, arg)
71 i -= 1
72 dict_foreach._annspecialcase_ = 'specialize:arg(1)'
73
74 ENTRY = lltype.Struct('ENTRY', ('key', llmemory.Address),
75 ('value', llmemory.Address))
76 ENTRIES = lltype.Array(ENTRY,
77 adtmeths = {
78 'allocate': dict_allocate_entries,
79 'delete': dict_delete_entries,
80 'valid': dict_entry_valid,
81 'everused': dict_entry_valid,
82 'hash': dict_entry_hash,
83 })
84 DICT = lltype.Struct('DICT', ('entries', lltype.Ptr(ENTRIES)),
85 ('num_items', lltype.Signed),
86 ('resize_counter', lltype.Signed),
87 adtmeths = {
88 'allocate': dict_allocate,
89 'delete': dict_delete,
90 'length': rdict.ll_dict_len,
91 'contains': rdict.ll_contains,
92 'setitem': rdict.ll_dict_setitem,
93 'get': dict_get,
94 'add': dict_add,
95 'insertclean': dict_insertclean,
96 'clear': rdict.ll_clear,
97 'foreach': dict_foreach,
98 'keyhash': dict_keyhash,
99 'keyeq': None,
100 })