-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathfixed-size.js
42 lines (34 loc) · 1003 Bytes
/
fixed-size.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
import { Uint8ArrayList } from 'uint8arraylist'
/**
* @type {import('../types').Chunker}
*/
async function * fixedSizeChunker (source, options) {
let list = new Uint8ArrayList()
let currentLength = 0
let emitted = false
const maxChunkSize = options.maxChunkSize
for await (const buffer of source) {
list.append(buffer)
currentLength += buffer.length
while (currentLength >= maxChunkSize) {
yield list.slice(0, maxChunkSize)
emitted = true
// throw away consumed bytes
if (maxChunkSize === list.length) {
list = new Uint8ArrayList()
currentLength = 0
} else {
const newBl = new Uint8ArrayList()
newBl.append(list.sublist(maxChunkSize))
list = newBl
// update our offset
currentLength -= maxChunkSize
}
}
}
if (!emitted || currentLength) {
// return any remaining bytes or an empty buffer
yield list.subarray(0, currentLength)
}
}
export default fixedSizeChunker