-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathrecord.js
59 lines (48 loc) · 1.42 KB
/
record.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
// SPDX-FileCopyrightText: 2022 Anders Rune Jensen
//
// SPDX-License-Identifier: LGPL-3.0-only
/*
Binary format for a Record:
<record>
<dataLength: UInt16LE>
<dataBuf: Arbitrary Bytes>
</record>
The "Header" is the first two bytes for the dataLength.
*/
const HEADER_SIZE = 2 // uint16
function size(dataBuf) {
return HEADER_SIZE + dataBuf.length
}
function readDataLength(blockBuf, offsetInBlock) {
return blockBuf.readUInt16LE(offsetInBlock)
}
function readSize(blockBuf, offsetInBlock) {
const dataLength = readDataLength(blockBuf, offsetInBlock)
return HEADER_SIZE + dataLength
}
function read(blockBuf, offsetInBlock) {
const dataLength = readDataLength(blockBuf, offsetInBlock)
const dataStart = offsetInBlock + HEADER_SIZE
const dataBuf = blockBuf.slice(dataStart, dataStart + dataLength)
const size = HEADER_SIZE + dataLength
return [dataBuf, size]
}
function write(blockBuf, offsetInBlock, dataBuf) {
blockBuf.writeUInt16LE(dataBuf.length, offsetInBlock) // write dataLength
dataBuf.copy(blockBuf, offsetInBlock + HEADER_SIZE) // write dataBuf
}
function overwriteWithZeroes(blockBuf, offsetInBlock) {
const dataLength = readDataLength(blockBuf, offsetInBlock)
const dataStart = offsetInBlock + HEADER_SIZE
const dataEnd = dataStart + dataLength
blockBuf.fill(0, dataStart, dataEnd)
}
module.exports = {
HEADER_SIZE,
size,
readDataLength,
readSize,
read,
write,
overwriteWithZeroes,
}