const Buffer = require('safe-buffer').Buffer module.exports = class BufferPipe { /** * Creates a new instance of a pipe * @param {Buffer} buf - an optional buffer to start with */ constructor (buf = Buffer.from([])) { this.buffer = buf this._bytesRead = 0 this._bytesWrote = 0 } /** * read `num` number of bytes from the pipe * @param {Number} num * @return {Buffer} */ read (num) { this._bytesRead += num const data = this.buffer.subarray(0, num) this.buffer = this.buffer.subarray(num) return data } /** * Wites a buffer to the pipe * @param {Buffer} buf */ write (buf) { buf = Buffer.from(buf) this._bytesWrote += buf.length this.buffer = Buffer.concat([this.buffer, buf]) } /** * Whether or not there is more data to read from the buffer * returns {Boolean} */ get end () { return !this.buffer.length } /** * returns the number of bytes read from the stream * @return {Integer} */ get bytesRead () { return this._bytesRead } /** * returns the number of bytes wrote to the stream * @return {Integer} */ get bytesWrote () { return this._bytesWrote } }