-
Notifications
You must be signed in to change notification settings - Fork 0
/
in-memory.js
62 lines (51 loc) · 1.46 KB
/
in-memory.js
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
const fs = require('fs')
// a very simple, unoptimized store provided as an example implementation & last-chance default
module.exports = class {
constructor() {
this.store = {};
}
getbit(key, bitPosition) {
if (key in this.store) {
const byteIdx = Math.floor(bitPosition / 8);
const innerPos = (bitPosition % 8);
const bitMask = 0x80 >> innerPos;
if (byteIdx in this.store[key]) {
return (this.store[key][byteIdx] & bitMask) >> (7 - innerPos);
}
}
return 0;
}
setbit(key, bitPosition, value) {
if (!(key in this.store)) {
this.store[key] = [];
}
const byteIdx = Math.floor(bitPosition / 8);
const bitMask = 0x80 >> (bitPosition % 8);
// lazily initialize everything up to and including byteIdx, if it isn't already initialized
if (!(byteIdx in this.store[key])) {
for (let bi = 0; bi <= byteIdx; bi++) {
if (!(bi in this.store[key])) {
this.store[key][bi] = 0;
}
}
}
if (value == true) {
this.store[key][byteIdx] |= bitMask;
} else {
this.store[key][byteIdx] &= ~bitMask;
}
}
getBuffer(key) {
if (!(key in this.store)) {
this.store[key] = [];
}
return Buffer.from(this.store[key]);
}
_unmarshalFrom(file) {
try { this.store = JSON.parse(fs.readFileSync(file)) }
catch {} // eslint-disable-line no-empty
}
_marshalTo(file) {
fs.writeFileSync(file, JSON.stringify(this.store))
}
}