-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathframe.js
67 lines (63 loc) · 1.97 KB
/
frame.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
63
64
65
66
67
var result = {start: -1, length: -1, offset: -1}
module.exports = {
encode: function (block, array, b) {
var c = 0
var offsets = []
for(var i = 0; i<array.length; i++) {
var length = array[i].length
//the buffer is full, pad end.
if(c+length+4 >= block-6) {
b.fill(0, c+2, block)
b.writeUInt32LE(c, block-4) //write pointer to last item
b.writeUInt16LE(block-1, c)
if(c >= block-6) throw new Error('block overlaps:'+c+', '+(block-6))
return offsets
}
else {
b.writeUInt16LE(length, c)
array[i].copy(b, c+2, 0, length)
b.writeUInt16LE(length, c+length+2)
offsets.push(c)
c+=length+4
}
}
return offsets
},
getBlockIndex: function (block, offset) {
return ~~(offset/block)
},
getBlockStart: function (block, offset) {
return offset % block
},
//getRecord(buffer, 0) for first record in block
getRecord: function (block, buffer, offset) {
var start = offset % block
var length = buffer.readUInt16LE(start)
if(length === block - 1)
return null
else {
var _length = buffer.readUInt16LE(start+2+length)
if(_length != length)
throw new Error('expected matching length at end, expected:'+length+', was:'+_length+' on block:'+block+' at offset:'+offset)
result.offset = offset
result.start = start+2
result.length = length
return result
}
},
getLastRecord: function (block, buffer, offset) {
var fromEnd = 4
var start = buffer.readUInt32LE(block - fromEnd)
while (start == 0 && fromEnd < block) { // find the last record
fromEnd += 4
start = buffer.readUInt32LE(block - fromEnd)
}
return module.exports.getPreviousRecord(block, buffer, offset-block + start)
},
getPreviousRecord: function (block, buffer, offset) {
var start = offset%block
if(start == 0) return
var length = buffer.readUInt16LE(start-2)
return offset - length - 4
}
}