forked from dignifiedquire/pull-block
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
87 lines (73 loc) · 2.05 KB
/
index.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
'use strict'
var through = require('pull-through')
var Buffer = require('safe-buffer').Buffer
function lazyConcat (buffers) {
if (buffers.length === 1) return buffers[0]
return Buffer.concat(buffers)
}
module.exports = function block (size, opts) {
if (!opts) opts = {}
if (typeof size === 'object') {
opts = size
size = opts.size
}
size = size || 512
var zeroPadding
if (opts.nopad) {
zeroPadding = false
} else {
zeroPadding = typeof opts.zeroPadding !== 'undefined' ? opts.zeroPadding : true
}
var buffered = []
var bufferedBytes = 0
var bufferSkip = 0
var emittedChunk = false
return through(function transform (data) {
if (typeof data === 'number') {
data = Buffer.from([data])
}
bufferedBytes += data.length
buffered.push(data)
while (bufferedBytes >= size) {
var targetLength = 0
var target = []
var b, end, out
while (targetLength < size) {
b = buffered[0]
// Slice as much as we can from the next buffer.
end = Math.min(bufferSkip + size - targetLength, b.length)
out = b.slice(bufferSkip, end)
targetLength += out.length
target.push(out)
if (end === b.length) {
// If that "consumes" the buffer, remove it.
buffered.shift()
bufferSkip = 0
} else {
// Otherwise keep track of how much we used.
bufferSkip += out.length
}
}
bufferedBytes -= targetLength
this.queue(lazyConcat(target))
emittedChunk = true
}
}, function flush (end) {
if ((opts.emitEmpty && !emittedChunk) || bufferedBytes) {
if (zeroPadding) {
var zeroes = Buffer.alloc(size - bufferedBytes)
zeroes.fill(0)
buffered.push(zeroes)
}
if (buffered) {
if (buffered.length > 0) {
// Don't copy the bufferSkip bytes through concat.
buffered[0] = buffered[0].slice(bufferSkip)
}
this.queue(lazyConcat(buffered))
buffered = null
}
}
this.queue(null)
})
}