Last active
December 3, 2015 11:13
-
-
Save oprypin/819d14d00c79e47e27d9 to your computer and use it in GitHub Desktop.
File-based integer key-value store
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import struct | |
store_fn = 'store' | |
#key_bits = 16 | |
#value_bits = 16 | |
#struct_format = 'H' | |
key_bits = 32 | |
value_bits = 32 | |
struct_format = 'I' | |
value_bytes = value_bits//8 | |
value_struct = struct.Struct(struct_format) | |
def make_store(): | |
with open(store_fn, 'wb') as f: | |
for i in range(2**key_bits * value_bytes): | |
f.write(b'\x00') | |
make_store() | |
store = open(store_fn, 'rb+') | |
def get(key): | |
store.seek(key * value_bytes) | |
data = store.read(value_bytes) | |
[value] = value_struct.unpack(data) | |
return value | |
def put(key, value): | |
store.seek(key * value_bytes) | |
data = value_struct.pack(value) | |
store.write(data) | |
put(123, 456) | |
print(get(65535)) | |
put(65535, 65535) | |
print(get(123)) | |
print(get(65535)) | |
store.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment