fastconstmap 0.11.1__cp315-cp315-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,38 @@
1
+ """fastconstmap — fast, immutable map from strings to 64-bit integers.
2
+
3
+ Build a compact lookup structure from any ``dict[str, int]`` (or
4
+ ``dict[bytes, int]``). Lookup costs one xxhash and three array reads.
5
+
6
+ Three classes are exposed:
7
+
8
+ * :class:`ConstMap` — minimal, ~9 bytes/key. Returns undefined values for
9
+ keys that were not in the original mapping. Use when you know upstream
10
+ that you will only look up keys you inserted.
11
+ * :class:`VerifiedConstMap` — ~18 bytes/key. Detects missing keys with
12
+ probability ~1 − 2⁻⁶⁴. Behaves like a normal ``dict``: ``m[k]`` raises
13
+ :class:`KeyError`, ``m.get(k, default)`` returns ``default``, ``k in m``
14
+ works.
15
+ * :class:`PairedVerifiedConstMap` — same size and behaviour as
16
+ :class:`VerifiedConstMap`, but stores each value next to its check word so
17
+ a lookup of a present key touches three cache lines instead of six (and
18
+ reads each as one 128-bit word on x86-64 and AArch64). Faster when most
19
+ lookups hit; slower when most miss. Its serialised form is not
20
+ interchangeable with :class:`VerifiedConstMap`'s.
21
+
22
+ All three are immutable after construction and can be serialised to bytes
23
+ or to a file path, in a format shared with the Go (``constmap``) and Rust
24
+ (``rsconstmap``) implementations: a file saved by any of the three loads in
25
+ the other two, on a little-endian host. Pass ``hash="xxh3"`` to a constructor
26
+ for a faster key hash whose files only fastconstmap reads. All also take batches: ``get_many`` returns a list, and
27
+ ``get_many_into`` writes 64-bit words straight into a buffer you own (an
28
+ ``array("Q")``, a numpy ``uint64`` array, a ``SharedMemory`` block), which
29
+ allocates nothing per key. A batch is faster than a loop because the map
30
+ hashes a block of keys before gathering any values, so the array reads of a
31
+ whole block overlap instead of being paid one after another. They can also be placed in a ``multiprocessing``
32
+ ``SharedMemory`` block and opened by many processes with no per-process
33
+ copy — see ``serialized_size``, ``write_into`` and ``from_buffer``.
34
+ """
35
+ from ._fastconstmap import ConstMap, VerifiedConstMap, PairedVerifiedConstMap, NOT_FOUND
36
+
37
+ __all__ = ["ConstMap", "VerifiedConstMap", "PairedVerifiedConstMap", "NOT_FOUND"]
38
+ __version__ = "0.10.0"
@@ -0,0 +1,111 @@
1
+ """Type stubs for the fastconstmap C extension."""
2
+ from __future__ import annotations
3
+ from os import PathLike
4
+ from typing import Iterable, Literal, Mapping, Optional, Union
5
+
6
+ KeyT = Union[str, bytes]
7
+ HashT = Literal["xxh64", "xxh3"]
8
+ PathT = Union[str, bytes, PathLike[str], PathLike[bytes]]
9
+ BufferT = Union[bytes, bytearray, memoryview]
10
+ WritableBufferT = Union[bytearray, memoryview]
11
+
12
+ NOT_FOUND: int
13
+ """Sentinel (2**64 - 1) written by ``VerifiedConstMap.get_many_into`` and
14
+ ``PairedVerifiedConstMap.get_many_into`` for a key
15
+ that was not in the original mapping."""
16
+
17
+
18
+ class ConstMap:
19
+ """Immutable map from strings to uint64.
20
+
21
+ Returns an undefined value for keys not present in the original mapping.
22
+ Memory: roughly 9 bytes per key.
23
+ """
24
+
25
+ def __init__(self, mapping: Mapping[KeyT, int], hash: HashT = "xxh64") -> None: ...
26
+ @property
27
+ def hash(self) -> HashT: ...
28
+ def __getitem__(self, key: KeyT) -> int: ...
29
+ def __len__(self) -> int: ...
30
+ def get(self, key: KeyT) -> int: ...
31
+ def get_many(self, keys: Iterable[KeyT]) -> list[int]: ...
32
+ def get_many_into(self, keys: Iterable[KeyT], out: WritableBufferT) -> int: ...
33
+ def to_bytes(self) -> bytes: ...
34
+ @classmethod
35
+ def from_bytes(cls, data: BufferT) -> "ConstMap": ...
36
+ def serialized_size(self) -> int: ...
37
+ def write_into(self, buffer: BufferT) -> int: ...
38
+ @classmethod
39
+ def from_buffer(cls, buffer: BufferT) -> "ConstMap": ...
40
+ def save(self, path: PathT) -> None: ...
41
+ @classmethod
42
+ def load(cls, path: PathT) -> "ConstMap": ...
43
+ def nbytes(self) -> int: ...
44
+
45
+
46
+ class VerifiedConstMap:
47
+ """Immutable map from strings to uint64 with missing-key detection.
48
+
49
+ ``m[key]`` raises ``KeyError`` if the key was not in the original mapping.
50
+ ``m.get(key, default=None)`` returns ``default`` instead. ``key in m``
51
+ tests membership.
52
+
53
+ Memory: roughly 18 bytes per key.
54
+ """
55
+
56
+ def __init__(self, mapping: Mapping[KeyT, int], hash: HashT = "xxh64") -> None: ...
57
+ @property
58
+ def hash(self) -> HashT: ...
59
+ def __getitem__(self, key: KeyT) -> int: ...
60
+ def __contains__(self, key: object) -> bool: ...
61
+ def __len__(self) -> int: ...
62
+ def get(self, key: KeyT, default: Optional[int] = None) -> Optional[int]: ...
63
+ def get_many(self, keys: Iterable[KeyT], default: Optional[int] = None) -> list[Optional[int]]: ...
64
+ def get_many_into(self, keys: Iterable[KeyT], out: WritableBufferT) -> int: ...
65
+ def to_bytes(self) -> bytes: ...
66
+ @classmethod
67
+ def from_bytes(cls, data: BufferT) -> "VerifiedConstMap": ...
68
+ def serialized_size(self) -> int: ...
69
+ def write_into(self, buffer: BufferT) -> int: ...
70
+ @classmethod
71
+ def from_buffer(cls, buffer: BufferT) -> "VerifiedConstMap": ...
72
+ def save(self, path: PathT) -> None: ...
73
+ @classmethod
74
+ def load(cls, path: PathT) -> "VerifiedConstMap": ...
75
+ def nbytes(self) -> int: ...
76
+
77
+
78
+ class PairedVerifiedConstMap:
79
+ """VerifiedConstMap with each value stored next to its check word.
80
+
81
+ Same API and size; a present-key lookup touches three cache lines
82
+ instead of six. Faster when most lookups hit, slower when most miss.
83
+ Serialised bytes are not interchangeable with ``VerifiedConstMap``.
84
+
85
+ ``m[key]`` raises ``KeyError`` if the key was not in the original mapping.
86
+ ``m.get(key, default=None)`` returns ``default`` instead. ``key in m``
87
+ tests membership.
88
+
89
+ Memory: roughly 18 bytes per key.
90
+ """
91
+
92
+ def __init__(self, mapping: Mapping[KeyT, int], hash: HashT = "xxh64") -> None: ...
93
+ @property
94
+ def hash(self) -> HashT: ...
95
+ def __getitem__(self, key: KeyT) -> int: ...
96
+ def __contains__(self, key: object) -> bool: ...
97
+ def __len__(self) -> int: ...
98
+ def get(self, key: KeyT, default: Optional[int] = None) -> Optional[int]: ...
99
+ def get_many(self, keys: Iterable[KeyT], default: Optional[int] = None) -> list[Optional[int]]: ...
100
+ def get_many_into(self, keys: Iterable[KeyT], out: WritableBufferT) -> int: ...
101
+ def to_bytes(self) -> bytes: ...
102
+ @classmethod
103
+ def from_bytes(cls, data: BufferT) -> "PairedVerifiedConstMap": ...
104
+ def serialized_size(self) -> int: ...
105
+ def write_into(self, buffer: BufferT) -> int: ...
106
+ @classmethod
107
+ def from_buffer(cls, buffer: BufferT) -> "PairedVerifiedConstMap": ...
108
+ def save(self, path: PathT) -> None: ...
109
+ @classmethod
110
+ def load(cls, path: PathT) -> "PairedVerifiedConstMap": ...
111
+ def nbytes(self) -> int: ...
fastconstmap/py.typed ADDED
File without changes
@@ -0,0 +1,463 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastconstmap
3
+ Version: 0.11.1
4
+ Summary: Fast, immutable, compact map from strings to uint64 (binary fuse filter).
5
+ Author-email: Daniel Lemire <daniel@lemire.me>
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/lemire/fastconstmap
8
+ Project-URL: Source, https://github.com/lemire/fastconstmap
9
+ Classifier: License :: OSI Approved :: Apache Software License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: Free Threading :: 3 - Stable
12
+ Classifier: Programming Language :: C
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # fastconstmap
21
+
22
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
23
+ [![Test](https://github.com/lemire/fastconstmap/actions/workflows/test.yml/badge.svg)](https://github.com/lemire/fastconstmap/actions/workflows/test.yml)
24
+
25
+ Fast, immutable, compact map from strings to 64-bit integers — for Python.
26
+
27
+ `fastconstmap` is a C implementation of the [binary fuse filter][bff]
28
+ construction (a static perfect-hash-like structure), exposed to Python.
29
+ Given a `dict[str, int]` at build time, you get back a lookup object that:
30
+
31
+ - uses **~9 bytes per key** (or ~18 with missing-key detection),
32
+ - answers a lookup in **one xxhash call plus three array reads**,
33
+ - is **immutable** and **serializable** to bytes / a file, in a format the
34
+ Go and Rust implementations read too,
35
+ - exposes both a single-key API (`m[key]`) and a **batched** API
36
+ (`m.get_many([...])`, `m.get_many_into([...], buf)`) that amortises Python-C
37
+ call overhead and overlaps the memory accesses of a whole block of keys.
38
+
39
+ This package is a C port of the Go library
40
+ [`github.com/lemire/constmap`][constmap]. It vendors
41
+ [xxHash](https://github.com/Cyan4973/xxHash) (BSD-2) for string hashing.
42
+
43
+ ## Installation
44
+
45
+ ```
46
+ pip install fastconstmap
47
+ ```
48
+
49
+ To build from source you need a C compiler. There are no Python runtime
50
+ dependencies.
51
+
52
+ ## Usage
53
+
54
+ ```python
55
+ from fastconstmap import ConstMap, VerifiedConstMap, PairedVerifiedConstMap
56
+
57
+ d = {"apple": 100, "banana": 200, "cherry": 300}
58
+
59
+ # Variant 1: minimal memory, no missing-key detection.
60
+ m = ConstMap(d)
61
+ m["apple"] # -> 100
62
+ m.get_many(["banana", "cherry"]) # -> [200, 300]
63
+ m["grape"] # undefined value! use VerifiedConstMap if you care.
64
+
65
+ # Variant 2: dict-like, detects keys not in the original mapping.
66
+ vm = VerifiedConstMap(d)
67
+ vm["apple"] # -> 100
68
+ vm.get("grape") # -> None
69
+ vm.get("grape", -1) # -> -1
70
+ "grape" in vm # -> False
71
+ vm["grape"] # raises KeyError
72
+ vm.get_many(["banana", "grape"], default=-1) # -> [200, -1]
73
+
74
+ # Variant 3: same as VerifiedConstMap, laid out for fewer cache misses when
75
+ # the keys you look up are usually present.
76
+ pm = PairedVerifiedConstMap(d)
77
+ pm["apple"] # -> 100
78
+ pm.get("grape") # -> None
79
+
80
+ # Batches can also be written straight into a buffer you own — no list of
81
+ # Python ints is built.
82
+ import array
83
+ out = array.array("Q", [0]) * 3
84
+ m.get_many_into(["apple", "banana", "cherry"], out) # -> 3; out == [100, 200, 300]
85
+
86
+ # Any kind can be saved and loaded.
87
+ m.save("mymap.cmap")
88
+ m2 = ConstMap.load("mymap.cmap")
89
+
90
+ # ... or as raw bytes.
91
+ blob = m.to_bytes()
92
+ m3 = ConstMap.from_bytes(blob)
93
+ ```
94
+
95
+ ### Choosing between `ConstMap`, `VerifiedConstMap` and `PairedVerifiedConstMap`
96
+
97
+ | | `ConstMap` | `VerifiedConstMap` | `PairedVerifiedConstMap` |
98
+ |--|--|--|--|
99
+ | Bytes per key | ~9 | ~18 | ~18 |
100
+ | Lookup of present key | value | value | value |
101
+ | Lookup of missing key | **undefined garbage** | `KeyError` / `default` / `None` | same |
102
+ | Cache lines touched per lookup | 3 | 6 (3 on a miss) | 3 |
103
+ | Best if | you always look up known keys | you need dict-like semantics and most lookups miss | you need dict-like semantics and most lookups hit |
104
+
105
+ The false-positive rate of the verified maps (a missing key wrongly
106
+ reported as present) is roughly 2⁻⁶⁴, which is negligible in practice.
107
+
108
+ `VerifiedConstMap` keeps its values and its 64-bit check words in two
109
+ separate arrays. A lookup reads three check words, and if they match, three
110
+ value words: six cache lines, in two different arrays. `PairedVerifiedConstMap`
111
+ is the same map with each value stored next to its check word, so the three
112
+ reads bring in both at once (three cache lines), and on x86-64 and AArch64
113
+ each slot is loaded and XORed as one 128-bit word (SSE2 / NEON).
114
+
115
+ The trade-off is what happens on a **miss**. With the split layout, a
116
+ one-at-a-time lookup of an absent key reads only the check array, which is
117
+ half the size of the whole map and so far more likely to be sitting in cache.
118
+ The paired layout always pulls in the value alongside the check, so its
119
+ working set for misses is twice as large. In batched lookups
120
+ (`get_many`, `get_many_into`) the split layout gathers both arrays
121
+ unconditionally, so there the paired layout wins whether keys hit or miss.
122
+
123
+ Measured at the C level (`fcm_*_lookup`, one key at a time, random order
124
+ over the whole key set, best of five), ns per lookup, *hit* = key present,
125
+ *miss* = key absent:
126
+
127
+ | | keys | `VerifiedConstMap` hit | `PairedVerifiedConstMap` hit | `VerifiedConstMap` miss | `PairedVerifiedConstMap` miss |
128
+ |--|--|--|--|--|--|
129
+ | Apple M4 Max | 1M | 9.9 | 9.5 | **6.4** | 8.8 |
130
+ | | 10M | 20.9 | **17.1** | **15.5** | 17.1 |
131
+ | Xeon Gold 6548N | 1M | 17.3 | **12.8** | 13.8 | 13.0 |
132
+ | | 10M | 44.4 | **37.3** | **31.8** | 37.4 |
133
+
134
+ The two serialised formats are the same size but not interchangeable:
135
+ loading one class's bytes with the other raises `ValueError`.
136
+
137
+ ## Batched lookups
138
+
139
+ `get_many` takes an iterable of keys and returns a list of values, in the same
140
+ order:
141
+
142
+ ```python
143
+ cm.get_many(["apple", "banana", "cherry"]) # -> [100, 200, 300]
144
+ vm.get_many(["banana", "grape"], default=-1) # -> [200, -1]
145
+ ```
146
+
147
+ `get_many_into` is the same lookup writing 64-bit words into a buffer you own,
148
+ so a repeated batch allocates nothing at all — no list, and no Python `int` per
149
+ key. The buffer can be an `array("Q")`, a numpy `uint64` array, a
150
+ `SharedMemory` block, or any other writable buffer of at least `8 * len(keys)`
151
+ bytes. It returns the number of values written:
152
+
153
+ ```python
154
+ import array
155
+ out = array.array("Q", [0]) * 4096
156
+ for batch in batches:
157
+ n = cm.get_many_into(batch, out)
158
+ use(out[:n])
159
+ ```
160
+
161
+ `VerifiedConstMap.get_many_into` writes `fastconstmap.NOT_FOUND` (`2**64 - 1`)
162
+ for a key that was not in the original mapping — a buffer of raw words has no
163
+ room for a Python default.
164
+
165
+ A batch is faster than a loop over single lookups because it hashes a block of
166
+ eight keys before gathering any values. That lets the three array reads of all
167
+ eight keys be in flight at once, instead of each key's loads waiting behind the
168
+ hashing of the key before it. A lookup is memory-latency bound as soon as the
169
+ map outgrows the last-level cache, which is where the gain comes from.
170
+
171
+ ### Measured
172
+
173
+ At the C level, 2000-key batches against a 1,000,000-key map, ns/key, medians
174
+ of three runs (`benchmarks/bench_batch.c`). *Cold* rotates through 64 distinct
175
+ random batches so the cache lines the lookups touch are not already resident;
176
+ *hot* replays one batch, so the touched region stays cache-resident and hashing
177
+ dominates instead.
178
+
179
+ | | | loop over lookup | `lookup_many` | |
180
+ |---|---|---|---|---|
181
+ | **Apple M4 Max** | `ConstMap` cold | 7.1 | **5.5** | 23% |
182
+ | | `ConstMap` hot | 6.1 | **4.6** | 24% |
183
+ | | `VerifiedConstMap` cold | 11.9 | **8.0** | 33% |
184
+ | | `VerifiedConstMap` hot | 7.4 | **5.8** | 21% |
185
+ | | `PairedVerifiedConstMap` cold | 10.8 | **7.3** | 32% |
186
+ | | `PairedVerifiedConstMap` hot | 6.6 | **4.8** | 27% |
187
+ | **Xeon Gold 6548N** | `ConstMap` cold | 19.1 | **13.6** | 29% |
188
+ | | `ConstMap` hot | 10.7 | **8.5** | 21% |
189
+ | | `VerifiedConstMap` cold | 21.8 | 21.9 | ~0% |
190
+ | | `VerifiedConstMap` hot | 12.6 | **10.5** | 17% |
191
+ | | `PairedVerifiedConstMap` cold | 21.0 | **15.0** | 29% |
192
+ | | `PairedVerifiedConstMap` hot | 12.5 | **9.9** | 21% |
193
+
194
+ These are with the default key hash, XXH64, which is what makes the files
195
+ interchangeable with the Go and Rust implementations (see
196
+ [Interoperability](#interoperability-with-the-go-and-rust-implementations)).
197
+ XXH3, the hash of 0.9 and earlier, is about 1.3 ns faster per 20-byte key on
198
+ the M4 Max and 2 ns on the Xeon; `ConstMap(d, hash="xxh3")` keeps it, at the
199
+ price of files only fastconstmap can read.
200
+
201
+ The one case where batching does not pay is `VerifiedConstMap` in the cold
202
+ regime on the Xeon. That map probes two arrays per lookup, so a fresh batch is
203
+ bound by a memory latency the overlapping cannot hide. The Go original reports
204
+ the same result on the same processor.
205
+
206
+ Through the Python API, ns/key on the same batches — 0.8.0 is the previous
207
+ per-key loop, 0.9.0 the batched path (both measured with XXH3; with the
208
+ default XXH64 of 0.10, add roughly 1-4 ns/key to the batched columns, and
209
+ 1-5 ns to a single `m[k]` that costs 50-120 ns):
210
+
211
+ | | | 0.8.0 | 0.9.0 | `get_many_into` |
212
+ |---|---|---|---|---|
213
+ | **Apple M4 Max** | `ConstMap` cold | 30.7 | **20.6** | **14.2** |
214
+ | | `ConstMap` hot | 16.4 | **14.1** | **6.1** |
215
+ | | `VerifiedConstMap` cold | 35.5 | 35.3 | **23.9** |
216
+ | **Xeon Gold 6548N** | `ConstMap` cold | 34.9 | **25.5** | **16.5** |
217
+ | | `ConstMap` hot | 18.7 | **17.2** | **8.8** |
218
+ | | `VerifiedConstMap` cold | 37.6 | **31.9** | **23.3** |
219
+
220
+ What is left in the `get_many` column is the cost of boxing each value in a
221
+ Python `int` and building the list, which is why `get_many_into` — which does
222
+ neither — is another 30-60% faster again.
223
+
224
+ To reproduce:
225
+
226
+ ```
227
+ cc -O3 -std=c11 -Isrc benchmarks/bench_batch.c src/constmap.c -lm -o bench_batch
228
+ ./bench_batch 1000000
229
+ ```
230
+
231
+ ## Keys and values
232
+
233
+ - **Keys** may be `str` or `bytes`. `str` is encoded as UTF-8 internally;
234
+ lookups must use the same encoding to match.
235
+ - **Values** are 64-bit integers. We accept anything in
236
+ `[-2**63, 2**64 - 1]`; negatives are stored via two's complement, so
237
+ `m[k]` returns `2**64 - 1` for a value of `-1`. (To recover the signed
238
+ reading, reinterpret bits yourself.)
239
+
240
+ Keys must be unique (Python dict semantics already guarantee this).
241
+ Construction raises `ValueError` in the extremely unlikely event of an
242
+ xxhash collision (~2⁻⁶⁴ per key pair).
243
+
244
+ ## Sharing a map across processes (zero-copy)
245
+
246
+ A map's serialized form *is* its in-memory lookup array (plus a small
247
+ header). That means it can live in a
248
+ [`multiprocessing.shared_memory`](https://docs.python.org/3/library/multiprocessing.shared_memory.html)
249
+ block and be opened by any number of processes **without copying** — every
250
+ process reads the same physical pages.
251
+
252
+ Three methods make this work:
253
+
254
+ | Method | Purpose |
255
+ |--|--|
256
+ | `m.serialized_size()` | bytes needed to hold the serialized map |
257
+ | `m.write_into(buffer)` | serialize straight into a writable buffer (no intermediate `bytes`) |
258
+ | `ConstMap.from_buffer(buffer)` | open a **zero-copy** map that reads directly from `buffer` |
259
+
260
+ Producer — build once, publish into a **named** shared-memory block:
261
+
262
+ ```python
263
+ from multiprocessing.shared_memory import SharedMemory
264
+ from fastconstmap import ConstMap
265
+
266
+ SHM_NAME = "fastconstmap_demo"
267
+
268
+ cm = ConstMap({f"key-{i}": i for i in range(1_000_000)})
269
+
270
+ shm = SharedMemory(create=True, size=cm.serialized_size(), name=SHM_NAME)
271
+ cm.write_into(shm.buf)
272
+ # keep `shm` alive (do not close/unlink) while consumers are running
273
+ ```
274
+
275
+ Consumer — attach to the same name with no copy:
276
+
277
+ ```python
278
+ from multiprocessing.shared_memory import SharedMemory
279
+ from fastconstmap import ConstMap
280
+
281
+ SHM_NAME = "fastconstmap_demo"
282
+
283
+ shm = SharedMemory(name=SHM_NAME) # attach by name, no `create=`
284
+ cm = ConstMap.from_buffer(shm.buf) # zero-copy: no per-process copy
285
+ cm["key-42"] # reads straight from shared memory
286
+ ```
287
+
288
+ Choosing the name yourself (rather than letting `SharedMemory` generate
289
+ one) means consumers can hard-code it or read it from config — no need to
290
+ pass the auto-generated name around. Pick a unique name; creating a block
291
+ whose name already exists raises `FileExistsError`.
292
+
293
+ Notes and constraints:
294
+
295
+ - **`from_buffer` does not copy.** The returned map holds a reference to the
296
+ buffer; the buffer (and, for shared memory, the `SharedMemory` object)
297
+ must stay alive and **must not be closed or mutated** while the map is in
298
+ use. Drop the map (`del cm`) before calling `shm.close()`.
299
+ - The map is **immutable** — the intended pattern is *write once in the
300
+ producer, then only read in every process*. Concurrent readers need no
301
+ locking (see [Threads](#threads-and-free-threaded-python)).
302
+ - `from_buffer` verifies the magic bytes and the FNV-1a checksum, so a
303
+ truncated or corrupt block raises `ValueError` rather than returning
304
+ garbage.
305
+ - Requirements: a **little-endian** host (x86-64, ARM64, …) and an
306
+ **8-byte-aligned** buffer. `SharedMemory.buf`, `bytes`, and `bytearray`
307
+ all satisfy the alignment requirement; an offset slice of a buffer may
308
+ not, in which case `from_buffer` raises `ValueError` — use
309
+ `from_bytes()` (which copies) instead.
310
+ - `VerifiedConstMap` and `PairedVerifiedConstMap` support the same three
311
+ methods.
312
+
313
+ `from_bytes()` remains available when you *want* an owned copy (or need to
314
+ load on a big-endian host): it copies the data and the resulting map owns
315
+ its memory independently of the source buffer.
316
+
317
+ ## Threads and free-threaded Python
318
+
319
+ The maps are immutable, so any number of threads can look up keys in the
320
+ same map at once, without locking. The extension supports free-threaded
321
+ Python (3.13t, 3.14t): it does not re-enable the GIL on import, and lookups
322
+ from several threads then run in parallel.
323
+
324
+ ```python
325
+ from concurrent.futures import ThreadPoolExecutor
326
+
327
+ m = ConstMap(d)
328
+ with ThreadPoolExecutor(8) as pool:
329
+ results = list(pool.map(m.get_many, batches))
330
+ ```
331
+
332
+ Building a map from a dict that another thread is modifying is safe (on a
333
+ free-threaded build the map is built from a snapshot of the dict), and so is
334
+ a batched lookup over a list that another thread is modifying. `__init__` can only be called once on a
335
+ map; calling it again raises `TypeError` rather than replacing the data
336
+ under other readers.
337
+
338
+ ## Interoperability with the Go and Rust implementations
339
+
340
+ A map saved by any of [`constmap`][constmap] (Go), [`rsconstmap`][rsconstmap]
341
+ (Rust) and fastconstmap loads in the other two, on a little-endian host (which
342
+ is every mainstream one: x86-64, ARM64, RISC-V, Apple silicon). The three share
343
+ the key hash (XXH64), the mixing, the seed sequence and the layout, so for the
344
+ same input Go and Rust write byte-identical files, and fastconstmap writes the
345
+ same bytes apart from one header word:
346
+
347
+ | class | magic | notes |
348
+ |---|---|---|
349
+ | `ConstMap` | `CMAP0003` | Go and Rust write `CMAP0001`, the same format minus a 4-byte key count; all three read both |
350
+ | `VerifiedConstMap` | `VMAP0001` | identical; the header word Go and Rust leave zero holds the key count here |
351
+ | `PairedVerifiedConstMap` | `PMAP0001` | likewise |
352
+
353
+ ```python
354
+ m = ConstMap.load("built-by-go.cmap") # from constmap.SaveToFile / save_to_file
355
+ vm = VerifiedConstMap.load("built-by-rust.vmap")
356
+ ```
357
+
358
+ Two things to know about a map that came from Go or Rust:
359
+
360
+ - **`len(m)` is 0**, because those writers do not record the key count. Every
361
+ lookup is unaffected.
362
+ - **A Go or Rust `ConstMap` file (`CMAP0001`) cannot be opened with
363
+ `from_buffer`**: its 28-byte header leaves the array 4 bytes off an 8-byte
364
+ boundary in any aligned buffer, so `from_buffer` raises `ValueError`. `load`
365
+ and `from_bytes`, which copy, work as usual. The other two formats have a
366
+ 32-byte header and view fine.
367
+
368
+ **Files from fastconstmap 0.9 and earlier** (`CMAP0002` / `VCMP0002`) still
369
+ load and answer correctly: they were built with XXH3, and a map keeps the hash
370
+ its file was built with (`m.hash` tells you which). Re-saving such a map keeps
371
+ its legacy magic, since its table only answers to XXH3; Go and Rust name these
372
+ files in their error message. To get a file the other implementations read,
373
+ rebuild the map from its keys.
374
+
375
+ **Keeping XXH3.** XXH3 is faster than XXH64 on short keys, by about 1-2 ns per
376
+ lookup at the C level. If you do not need the shared format, build with
377
+ `ConstMap(d, hash="xxh3")` (likewise for the other two classes); such a map
378
+ serializes with the legacy magic, readable by fastconstmap only.
379
+
380
+ The interoperability is tested: `tests/interop/` holds files written by the Go
381
+ package from a fixed input, which the test suite loads and checks, and the Go
382
+ and Rust repositories hold files written by this package.
383
+
384
+ [rsconstmap]: https://github.com/lemire/rsconstmap
385
+
386
+ ## Benchmark
387
+
388
+ On an Apple M4 Max, with 1,000,000 string keys (`key-{i}-{hex}` shaped
389
+ strings). Lookups query every key exactly once, in random order, from a list
390
+ built in that order:
391
+
392
+ ```
393
+ === fastconstmap benchmark — n = 1,000,000 keys, python 3.14.5 ===
394
+
395
+ Construction:
396
+ ConstMap.__init__ 0.145 s
397
+ VerifiedConstMap.__init__ 0.142 s
398
+ dict(d) 0.004 s
399
+
400
+ Memory:
401
+ ConstMap.nbytes 9,043,968 bytes (9.04 bytes/key)
402
+ VerifiedConstMap.nbytes 18,087,936 bytes (18.09 bytes/key)
403
+ dict (table+keys+values) 118,380,958 bytes (118.38 bytes/key)
404
+ ratio dict / ConstMap 13.1x
405
+
406
+ Single lookup, every key once in random order (1,000,000 ops):
407
+ dict[k] 336.1 ns/op (0.336 s total)
408
+ ConstMap[k] 95.2 ns/op (0.095 s total)
409
+ VerifiedConstMap[k] 112.3 ns/op (0.112 s total)
410
+
411
+ Batched lookup, 2000 × 2000:
412
+ dict comprehension (cold) 148.7 ns/op (0.30 ms/batch of 2000)
413
+ ConstMap.get_many (cold) 24.2 ns/op (0.05 ms/batch of 2000)
414
+ ConstMap.get_many (hot) 15.6 ns/op (0.03 ms/batch of 2000)
415
+ ConstMap.get_many_into (cold) 14.2 ns/op (0.03 ms/batch of 2000)
416
+ ConstMap.get_many_into (hot) 6.1 ns/op (0.01 ms/batch of 2000)
417
+ VerifiedConstMap.get_many (cold) 33.7 ns/op (0.07 ms/batch of 2000)
418
+ VerifiedConstMap.get_many_into (cold) 23.9 ns/op (0.05 ms/batch of 2000)
419
+
420
+ Serialization:
421
+ ConstMap.to_bytes 0.010 s (9,044,008 bytes)
422
+ ConstMap.from_bytes 0.010 s
423
+ ```
424
+
425
+ The single-lookup numbers are dominated by Python call overhead, not by the
426
+ map: use `get_many` when you have an array of keys to look up at once, and
427
+ `get_many_into` when you have somewhere to put the results.
428
+
429
+ To reproduce:
430
+
431
+ ```
432
+ python benchmarks/benchmark.py 1000000
433
+ ```
434
+
435
+ ## How it works
436
+
437
+ Given *n* (key, value) pairs the algorithm:
438
+
439
+ 1. Hashes each key with XXH64 (or XXH3 if asked) to a 64-bit value.
440
+ 2. Maps each hashed key to three positions `h0, h1, h2` in an array of
441
+ size ~1.125·*n*, using overlapping segments.
442
+ 3. Finds, via [peeling][bff], an ordering in which each key has an
443
+ exclusive cell among its three; walks that ordering in reverse,
444
+ setting each cell so `array[h0] ^ array[h1] ^ array[h2] == value`.
445
+
446
+ Lookup is one xxhash, three array reads, and two XORs.
447
+
448
+ References:
449
+
450
+ > Thomas Mueller Graf and Daniel Lemire,
451
+ > [*Binary Fuse Filters: Fast and Smaller Than Xor Filters*][bff],
452
+ > ACM Journal of Experimental Algorithmics, Vol. 27, 2022.
453
+ > DOI: [10.1145/3510449](https://doi.org/10.1145/3510449)
454
+
455
+ ## License
456
+
457
+ Apache License 2.0. See [LICENSE](LICENSE).
458
+
459
+ `fastconstmap` vendors xxHash, which is licensed under the BSD-2-clause
460
+ license; see `src/third_party/xxhash/LICENSE`.
461
+
462
+ [bff]: https://arxiv.org/abs/2201.01174
463
+ [constmap]: https://github.com/lemire/constmap
@@ -0,0 +1,9 @@
1
+ fastconstmap/__init__.py,sha256=jjKU7WJhPi05lQZ3gmF7vuEF3OuwfPjb6ZK05m9Jo00,2284
2
+ fastconstmap/_fastconstmap.cp315-win_amd64.pyd,sha256=A7cqIQYjAK8Z_Z8vwAftdignhpWYxq2ILHyjU5PQCQk,64512
3
+ fastconstmap/_fastconstmap.pyi,sha256=88FBRuBoKSnRH7-0NUENjrQl1LDDRD7ezCwzufamXJk,4584
4
+ fastconstmap/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ fastconstmap-0.11.1.dist-info/licenses/LICENSE,sha256=gRp0dEaaLd9VdHCUFlT60zbHMqbZIkfFygsAse5tyO4,10954
6
+ fastconstmap-0.11.1.dist-info/METADATA,sha256=IewZ7De6kHaRRT_lEuUWCsGL3unmz08pUzB3ufMIEDo,20275
7
+ fastconstmap-0.11.1.dist-info/WHEEL,sha256=0gLwYZa0C2fhgCxWR2c8HahwUiopqonVCV0wVwEg6fE,101
8
+ fastconstmap-0.11.1.dist-info/top_level.txt,sha256=aJ2SymlkYOPJEM2yVHKSyUxHzYAEvpwwpsIqhnEPdtE,13
9
+ fastconstmap-0.11.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: false
4
+ Tag: cp315-cp315-win_amd64
5
+
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to the Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by the Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding any notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2024 Daniel Lemire
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
@@ -0,0 +1 @@
1
+ fastconstmap