git ssb

0+

wanderer🌟 / buffer-pipe



Tree: 91c8df6aec7c7dde118a5806a0365abdaef63dfc

Files: 91c8df6aec7c7dde118a5806a0365abdaef63dfc / index.js

1205 bytesRaw
1const Buffer = require('safe-buffer').Buffer
2
3module.exports = class BufferPipe {
4 /**
5 * Creates a new instance of a pipe
6 * @param {Buffer} buf - an optional buffer to start with
7 */
8 constructor (buf = Buffer.from([])) {
9 this.buffer = buf
10 this._bytesRead = 0
11 this._bytesWrote = 0
12 }
13
14 /**
15 * read `num` number of bytes from the pipe
16 * @param {Number} num
17 * @return {Buffer}
18 */
19 read (num) {
20 this._bytesRead += num
21 const data = this.buffer.subarray(0, num)
22 this.buffer = this.buffer.subarray(num)
23 return data
24 }
25
26 /**
27 * Wites a buffer to the pipe
28 * @param {Buffer} buf
29 */
30 write (buf) {
31 buf = Buffer.from(buf)
32 this._bytesWrote += buf.length
33 this.buffer = Buffer.concat([this.buffer, buf])
34 }
35
36 /**
37 * Whether or not there is more data to read from the buffer
38 * returns {Boolean}
39 */
40 get end () {
41 return !this.buffer.length
42 }
43
44 /**
45 * returns the number of bytes read from the stream
46 * @return {Integer}
47 */
48 get bytesRead () {
49 return this._bytesRead
50 }
51
52 /**
53 * returns the number of bytes wrote to the stream
54 * @return {Integer}
55 */
56 get bytesWrote () {
57 return this._bytesWrote
58 }
59}
60

Built with git-ssb-web