@@ -68,6 +68,48 @@ def test_items(ht12):
6868 assert (key2 , value2 ) in items
6969
7070
71+ @pytest .mark .parametrize ("prefix_bits" , [1 , 2 , 3 , 8 , 9 , 32 ])
72+ def test_items_prefix (ht , prefix_bits ):
73+ # pseudo-random keys, so (for small prefix_bits) all partitions should get some keys
74+ expected = {}
75+ for x in range (1000 ):
76+ key = H2 (x )
77+ value = key [:4 ]
78+ ht [key ] = value
79+ prefix = int .from_bytes (key [:4 ], "big" ) >> (32 - prefix_bits )
80+ expected .setdefault (prefix , set ()).add ((key , value ))
81+ # only iterate over the actually occupied partitions (2 ** 32 would take a while)...
82+ collected = []
83+ for prefix in expected :
84+ items = set (ht .items (prefix_bits = prefix_bits , prefix = prefix ))
85+ assert items == expected [prefix ]
86+ collected .extend (items )
87+ # together, the occupied partitions have everything, exactly once:
88+ assert len (collected ) == len (set (collected )) == 1000
89+ # ... but an unoccupied partition (if any) must yield nothing:
90+ unoccupied = next ((p for p in range (2 ** prefix_bits ) if p not in expected ), None )
91+ if unoccupied is not None :
92+ assert list (ht .items (prefix_bits = prefix_bits , prefix = unoccupied )) == []
93+
94+
95+ def test_items_prefix_zero_bits (ht12 ):
96+ # prefix_bits=0 means: no filtering
97+ assert set (ht12 .items (prefix_bits = 0 , prefix = 0 )) == set (ht12 .items ())
98+
99+
100+ def test_items_prefix_validation (ht12 ):
101+ with pytest .raises (ValueError ):
102+ list (ht12 .items (prefix_bits = - 1 ))
103+ with pytest .raises (ValueError ):
104+ list (ht12 .items (prefix_bits = 33 ))
105+ with pytest .raises (ValueError ):
106+ list (ht12 .items (prefix_bits = 0 , prefix = 1 ))
107+ with pytest .raises (ValueError ):
108+ list (ht12 .items (prefix_bits = 2 , prefix = 4 ))
109+ with pytest .raises (ValueError ):
110+ list (ht12 .items (prefix_bits = 2 , prefix = - 1 ))
111+
112+
71113def test_len (ht12 ):
72114 assert len (ht12 ) == 2
73115
0 commit comments