-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
539 lines (407 loc) · 10.1 KB
/
cache.go
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
package dejavu
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"sync"
)
const (
bitsPerByte = 8
maxUintLen32 = 4
)
// A Cache is a binary tree, held in memory as a byte array divided into
// segments of equal length, each representing a node in the tree.
//
// A node begins with a value of fixed length valLen, followed by two indices
// of length idxLen pointing to its left and right children.
//
// The Cache is insert-only and has a write lock to prevent concurrent writes.
type Cache struct {
memory []byte // pointer to array in memory holding binary tree
length int // number of values cached
mutex sync.Mutex // write lock
idxLen int // length of node indices, in number of bytes
valLen int // length of values, in number of bytes
maxCap int // maximum number of values that can be cached
}
// NewCache128 creates a new Cache that holds up to n 128-bit values in memory.
// Allocates an array of maximum size 96 GiB if n == math.MaxUint32.
func NewCache128(n uint32) *Cache {
return newCache(128, n)
}
// Length returns the number of values currently cached.
func (c *Cache) Length() int {
return c.length
}
// Size returns the size of the underlying array, in number of bytes.
func (c *Cache) Size() int {
return len(c.memory)
}
// Full returns true if the cache is full.
func (c *Cache) Full() (full bool) {
return c.length == c.maxCap
}
// Insert caches a value.
func (c *Cache) Insert(value []byte) (e error) {
defer errorf("could not insert", &e)
if c.Full() {
e = fmt.Errorf("no more free space left in cache")
return
}
if len(value) != c.valLen {
e = fmt.Errorf("value length not equal to %d bytes", c.valLen)
return
}
c.mutex.Lock()
defer c.mutex.Unlock()
c.insert(0, value)
return
}
// Recall returns true if a value has been cached, false otherwise.
func (c *Cache) Recall(value []byte) (cached bool, e error) {
defer errorf("could not recall", &e)
if len(value) != c.valLen {
e = fmt.Errorf("value length not equal to %d bytes", c.valLen)
return
}
return c.recall(0, value), nil
}
// Last returns the last-cached value, or an nil slice if the cache is empty.
func (c *Cache) Last() (value []byte) {
switch c.length {
case 0:
return
default:
value = c.val(c.length - 1)
}
return
}
// Save writes all cached values to an [io.Writer] in the order of their
// insertion, after sending metadata about value length and quantity.
func (c *Cache) Save(writer io.Writer) (e error) {
defer errorf("could not save", &e)
c.mutex.Lock()
var (
i int
length int = c.length
valLen int = c.valLen
)
c.mutex.Unlock()
e = binary.Write(writer, binary.BigEndian,
uint32(valLen),
)
if e != nil {
return
}
e = binary.Write(writer, binary.BigEndian,
uint32(length),
)
if e != nil {
return
}
for i = 0; i < length; i++ {
_, e = writer.Write(
c.val(i),
)
if e != nil {
return
}
}
return
}
// SaveOnto is like Save, but instead of writing all cached values, it appends
// only the last d values to a target [io.ReadWriteSeeker], overwriting
// metadata about value quantity. d is the difference between the number of
// cached values and number of values already written to the target by a
// previous invocation of Save or SaveOnto.
//
// If d is zero, then SaveOnto would write nothing, but nevertheless advance
// the offset for the next Read() or Write().
//
// The caller is responsible for seeking the target to the same offset as when
// Save or SaveOnto was previously called.
func (c *Cache) SaveOnto(target io.ReadWriteSeeker) (e error) {
defer errorf("could not save onto", &e)
c.mutex.Lock()
var (
cLength int = c.length
cValLen int = c.valLen
length uint32
valLen uint32
i int
)
c.mutex.Unlock()
e = binary.Read(target, binary.BigEndian, &valLen)
if e != nil {
return
}
if int(valLen) != cValLen {
e = fmt.Errorf("target value length %d bytes "+
"not equal to that of cached values, %d bytes",
valLen,
cValLen,
)
return
}
e = binary.Read(target, binary.BigEndian, &length)
if e != nil {
return
}
switch {
case int(length) > cLength:
e = fmt.Errorf("number of values in target %d "+
"is greater than the number of cached values, %d",
length,
cLength,
)
return
case int(length) < cLength:
_, e = target.Seek(-maxUintLen32, io.SeekCurrent)
if e != nil {
return
}
e = binary.Write(target, binary.BigEndian,
uint32(cLength),
)
if e != nil {
return
}
}
_, e = target.Seek(
int64(length*valLen),
io.SeekCurrent,
)
if e != nil {
return
}
for i = int(length); i < cLength; i++ {
_, e = target.Write(
c.val(i),
)
if e != nil {
return
}
}
return
}
// Counterpart to Save, Load reads and inserts values from an [io.Reader],
// after verifying metadata about inbound value length and quantity.
func (c *Cache) Load(reader io.Reader) (e error) {
defer errorf("could not load", &e)
var (
i uint32
length uint32
valLen uint32
value []byte
)
e = binary.Read(reader, binary.BigEndian, &valLen)
if e != nil {
return
}
e = binary.Read(reader, binary.BigEndian, &length)
if e != nil {
return
}
c.mutex.Lock()
defer c.mutex.Unlock()
if int(valLen) != c.valLen {
e = fmt.Errorf("value length not equal to %d bytes", c.valLen)
return
}
value = make([]byte, valLen)
if int(length) > (c.maxCap - c.length) {
e = fmt.Errorf("not enough free space left in cache")
return
}
for i = 0; i < length; i++ {
_, e = io.ReadFull(reader, value)
if e != nil {
return
}
c.insert(0, value)
}
return
}
func newCache(l uint8, n uint32) (c *Cache) {
// Creates a new Cache that holds up to n l-bit values in memory.
c = &Cache{
idxLen: log(int(n), bitsPerByte) / bitsPerByte,
valLen: int(l / bitsPerByte),
maxCap: int(n),
}
c.memory = make([]byte,
int(n)*c.nodeLen(),
)
return
}
func (c *Cache) insert(i int, val []byte) {
// Appends a new node to the array by setting its value, and updates its
// parent to point to it. Make sure this method is only called when the
// mutex is locked!
var (
left bool
next int
)
next, left = c.look(i, val)
switch next {
case -1: // do nothing; value already cached
return
case 0: // child does not exist; create child
c.setVal(c.length, val)
if left {
c.setIdxL(i, c.length)
} else {
c.setIdxR(i, c.length)
}
c.length++
default: // child exists; descend into child
c.insert(next, val)
}
return
}
func (c *Cache) recall(i int, val []byte) bool {
// Returns true if a node with value val is found; otherwise false.
var (
next int
)
next, _ = c.look(i, val)
switch next {
case -1: // value found
return true
case 0: // value not found
return false
default: // go deeper
return c.recall(next, val)
}
}
func (c *Cache) look(i int, val []byte) (int, bool) {
// Returns either
// (1) the index of the left child of the i-th node in the array, if
// val is less than the value of that node, or
// (2) the index of the right child, if val is greater, or
// (3) 0, if the relevant child does not exist, or
// (4) -1, if val is equal to the value of that node, and
// true if the index returned is of the left child of that node.
switch bytes.Compare(c.val(i), val) {
case 0:
return -1, false
case 1: // c.val(i) > val
return c.idxL(i), true
case -1: // c.val(i) < val
return c.idxR(i), false
}
return 0, false
}
func (c *Cache) val(i int) []byte {
// Returns the value of the i-th node in the array.
var (
valPos int = i * c.nodeLen()
)
return c.memory[valPos : valPos+c.valLen]
}
func (c *Cache) idxL(i int) int {
// Returns the index of the left child of the i-th node in the array.
var (
idxPos int = i*c.nodeLen() + c.valLen
idxVal uint32
)
idxVal = getUint32(c.memory[idxPos : idxPos+c.idxLen])
return int(idxVal)
}
func (c *Cache) idxR(i int) int {
// Returns the index of the right child of the i-th node in the array.
var (
idxPos int = i*c.nodeLen() + c.valLen + c.idxLen
idxVal uint32
)
idxVal = getUint32(c.memory[idxPos : idxPos+c.idxLen])
return int(idxVal)
}
func (c *Cache) setVal(i int, val []byte) {
// Overwrites the value of the i-th node in the array.
// Ensure it is only called while the mutex is locked!
var (
j int
valPos int = i * c.nodeLen()
)
// copy(c.memory[valPos:valPos+c.valLen], val)
for j = 0; j < len(val); j++ {
c.memory[valPos+j] = val[j]
}
return
}
func (c *Cache) setIdxL(i int, idxVal int) {
// Overwrites the index of the left child of the i-th node in the array.
// Ensure it is only called while the mutex is locked!
var (
idxPos int = i*c.nodeLen() + c.valLen
)
putUint32(c.memory[idxPos:idxPos+c.idxLen],
uint32(idxVal),
)
return
}
func (c *Cache) setIdxR(i int, idxVal int) {
// Overwrites the index of the right child of the i-th node in the array.
// Ensure it is only called while the mutex is locked!
var (
idxPos int = i*c.nodeLen() + c.valLen + c.idxLen
)
putUint32(c.memory[idxPos:idxPos+c.idxLen],
uint32(idxVal),
)
return
}
func (c *Cache) nodeLen() int {
// Returns the length of a node, in number of bytes.
return c.valLen + 2*c.idxLen
}
func log(n int, m int) (x int) {
// Returns x >= log2(n) such that x is a multiple of m, or 0 if n == 0.
if n == 0 {
return
}
for {
if 1<<x >= n {
break
}
x += m
}
return
}
func putUint32(into []byte, value uint32) {
// Copies the last bytes in the big-endian representation of value into a
// byte slice, sans leading zeroes.
var (
b = make([]byte, maxUintLen32)
i int
)
binary.BigEndian.PutUint32(b, value)
// copy(into, b[maxUintLen32-len(into):])
for i = 0; i < len(into); i++ {
into[i] = b[maxUintLen32-len(into)+i]
}
return
}
func getUint32(from []byte) uint32 {
// Returns a 32-bit unsigned integer given its big-endian representation.
// If shorter than four bytes, the representation is assumed to be
// right-aligned with leading zeroes omitted.
var (
b = make([]byte, maxUintLen32)
i int
)
// copy(b[maxUintLen32-len(from):], from)
for i = 0; i < len(from); i++ {
b[maxUintLen32-len(from)+i] = from[i]
}
return binary.BigEndian.Uint32(b)
}
func errorf(prefix string, errPtr *error) {
if *errPtr == nil {
return
}
*errPtr = fmt.Errorf("%s: %w", prefix, *errPtr)
return
}