-
Notifications
You must be signed in to change notification settings - Fork 8
/
reference-buffered-transform.js
70 lines (54 loc) · 1.66 KB
/
reference-buffered-transform.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
'use strict'
const { Buffer } = require('buffer')
const Status = require('./reference-status-enum')
class BufferedTransform {
constructor (bufferSize, reallocateSize) {
this.sink = null
this.source = null
this._buffer = Buffer.allocUnsafe(bufferSize)
this._bytes = 0
this._readPos = 0
this._reallocateSize = reallocateSize || bufferSize
}
bindSource (source) {
source.bindSink(this)
this.source = source
return this
}
bindSink (sink) {
this.sink = sink
}
next (status, error, buffer, bytes) {
if (status === Status.error) {
return this.sink.next(status, error)
}
if (status === Status.end) {
// Flush
return this.sink.next(status, null, this._buffer, this._bytes)
}
if (this._bytes + bytes > this._buffer.length) {
const prevBuffer = this._buffer
const reallocSize = this._buffer.length + this._reallocateSize
const neededSize = this._bytes + bytes
this._buffer = Buffer.allocUnsafe(neededSize > reallocSize ? neededSize + reallocSize : reallocSize)
prevBuffer.copy(this._buffer, 0, 0, neededSize)
}
buffer.copy(this._buffer, this._bytes, 0, bytes)
this._bytes += bytes
if (status === Status.continue) {
return this.source.pull(null, buffer)
}
}
pull (error, buffer) {
if (error !== null || this._bytes === 0) {
return this.source.pull(error, buffer)
}
if (this._readPos >= this._bytes) {
this.sink.next(Status.end)
}
this._buffer.copy(buffer, 0, this._readPos)
this._readPos += buffer.length
this.sink.next(Status.continue, null, buffer, buffer.length)
}
}
module.exports = BufferedTransform