Skip to content

Commit

Permalink
MemoryStream: add support to limit size of array buffer
Browse files Browse the repository at this point in the history
  • Loading branch information
wpjunior committed Dec 20, 2017
1 parent e616b57 commit 41e6d44
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 2 deletions.
20 changes: 18 additions & 2 deletions lib/MemoryStream.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,29 @@
const { Writable } = require('stream');

class MemoryStream extends Writable {
constructor() {
constructor(maxSize = -1) {
super();
this.buffer = [];
this.size = 0;
this.maxSize = maxSize;
this.truncated = false;
}

_write(chunk, encoding, done) {
this.buffer.push(chunk.toString());
if (this.truncated) {
done();
return;
}

let strChunk = chunk.toString();

if (this.maxSize > 0 && (this.size + strChunk.length) >= this.maxSize) {
strChunk = strChunk.slice(0, this.maxSize - this.size);
this.truncated = true;
}

this.size += strChunk.length;
this.buffer.push(strChunk);
done();
}
}
Expand Down
35 changes: 35 additions & 0 deletions test/MemoryStream.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const expect = require('chai').expect;
const MemoryStream = require('../lib/MemoryStream');

describe('MemoryStream', () => {
describe('#write', () => {
it('should write into buffer array', () => {
const stream = new MemoryStream();
stream.write('testing');
stream.write('foo');

expect(stream.buffer).to.be.eql([
'testing',
'foo',
]);
expect(stream.size).to.be.eql(10);
expect(stream.truncated).to.be.false;
});

describe('when stream have a maxSize', () => {
it('should limit the size of array buffer', () => {
const stream = new MemoryStream(9);
stream.write('testing');
stream.write('foo');
stream.write('bar');

expect(stream.buffer).to.be.eql([
'testing',
'fo',
]);
expect(stream.size).to.be.eql(9);
expect(stream.truncated).to.be.true;
});
});
});
});

0 comments on commit 41e6d44

Please sign in to comment.