-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNoDB.py
113 lines (100 loc) · 2.63 KB
/
NoDB.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import os
import sys
import struct
Nof = None
DBf = None
name = ""
N = 0
offset = 0
ENTRY_SIZE = struct.calcsize("!Q")
def create(file_name):
global Nof
global DBf
global name
global N
global offset
if Nof or DBf:
print "Attempted to initialize %s when %s was still open!" % (file_name, name)
sys.exit(-1)
#if os.path.exists(file_name+".No") or os.path.exists(file_name+".DB"):
# print "Attempted to recreate %s!!!" % file_name
# sys.exit(-1)
Nof = open(file_name+".No", 'wb')
DBf = open(file_name+".DB", 'wb')
N = 0
offset = 0
name = file_name
return N
def resume(file_name):
global Nof
global DBf
global name
global N
global offset
if Nof or DBf:
print "Attempted to initialize %s when %s was still open!" % (file_name, name)
sys.exit(-1)
if not os.path.exists(file_name+".No") or not os.path.exists(file_name+".DB"):
print "Failed to resume %s!!!" % file_name
sys.exit(-1)
N = os.path.getsize(file_name+".No") / ENTRY_SIZE
offset = os.path.getsize(file_name+".DB")
Nof = open(file_name+".No", 'ab')
DBf = open(file_name+".DB", 'ab')
name = file_name
return N
def close():
global Nof
global DBf
global name
global N
global offset
if not Nof or not DBf:
print "Attempted to close non-existent NoDB store!"
sys.exit(-1)
else:
Nof.close()
Nof = None
DBf.close()
DBf = None
name = ""
offset = 0
size = N
N = 0
return size
def store(byte_string):
global Nof
global DBf
global name
global N
global offset
if not Nof or not DBf:
print "Attempted to use NoDB store without initialization!"
sys.exit(-1)
DBf.write(byte_string)
N += 1
offset += len(byte_string)
Nof.write(struct.pack("!Q", offset))
assert Nof.tell() == N*ENTRY_SIZE
return N
def lookup(file_name, n):
# These are private by design!
N = os.path.getsize(file_name+".No") / ENTRY_SIZE
if n > N:
print "Attempted to lookup entry #%d from a DB of cardinality #%d!" % (n, N)
sys.exit(-1)
if n == 0:
print "Keys to NoDB must be natural numbers, starting from 1!"
sys.exit(-1)
Nof = open(file_name + ".No", 'rb')
start = 0
if n > 1:
Nof.seek(ENTRY_SIZE*(n-2))
start = struct.unpack("!Q", Nof.read(ENTRY_SIZE))[0]
stop = struct.unpack("!Q", Nof.read(ENTRY_SIZE))[0]
Nof.close()
DBf = open(file_name + ".DB", 'rb')
DBf.seek(start)
out = DBf.read(stop-start)
DBf.close()
return out