Created
November 30, 2011 08:23
-
-
Save redbo/1408423 to your computer and use it in GitHub Desktop.
This file contains 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 ctypes | |
import os | |
import mmap | |
class Record(ctypes.Structure): | |
_fields_ = [('index', ctypes.c_uint64), | |
('key_length', ctypes.c_uint16), | |
('key', ctypes.c_char * 256)] | |
RECORD_COUNT = 256 | |
file_size = ctypes.sizeof(Record) * RECORD_COUNT | |
with open('somefile', 'w+b') as fp: | |
os.ftruncate(fp.fileno(), file_size) | |
mem = mmap.mmap(fp.fileno(), file_size) | |
array = (Record * RECORD_COUNT).from_buffer(mem) | |
for i, item in enumerate(array): | |
item.index = i | |
item.key = 'item ' + str(i) | |
item.key_length = len(item.key) | |
mem.flush() | |
mem.close() | |
with open('somefile', 'r+b') as fp: | |
mem = mmap.mmap(fp.fileno(), file_size) | |
array = (Record * RECORD_COUNT).from_buffer(mem) | |
for i, item in enumerate(array): | |
assert(i == item.index) | |
assert('item ' + str(i) == item.key) | |
assert(len('item ' + str(i)) == item.key_length) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment