Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(parsers): ByteLength is now more efficient #1402

Merged
merged 1 commit into from
Nov 16, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 18 additions & 11 deletions lib/parsers/byte-length.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,16 @@ const Transform = require('stream').Transform;
/**
* A transform stream that emits data as a buffer after a specific number of bytes are received.
* @extends Transform
* @param {Object} options
* @param {Number} options.length the number of bytes on each data event
* @example
To use the `ByteLength` parser, provide the length of the number of bytes:
To use the `ByteLength` parser:
```js
const SerialPort = require('serialport');
const ByteLength = SerialPort.parsers.ByteLength
const port = new SerialPort('/dev/tty-usbserial1');
const parser = port.pipe(new ByteLength({length: 8}));
parser.on('data', console.log);
parser.on('data', console.log); // will have 8 bytes per data event
```
*/
class ByteLengthParser extends Transform {
Expand All @@ -29,23 +31,28 @@ class ByteLengthParser extends Transform {
}

this.length = options.length;
this.buffer = Buffer.alloc(0);
this.position = 0;
this.buffer = Buffer.alloc(this.length);
}

_transform(chunk, encoding, cb) {
let data = Buffer.concat([this.buffer, chunk]);
while (data.length >= this.length) {
const out = data.slice(0, this.length);
this.push(out);
data = data.slice(this.length);
let cursor = 0;
while (cursor < chunk.length) {
this.buffer[this.position] = chunk[cursor];
cursor++;
this.position++;
if (this.position === this.length) {
this.push(this.buffer);
this.buffer = Buffer.alloc(this.length);
this.position = 0;
}
}
this.buffer = data;
cb();
}

_flush(cb) {
this.push(this.buffer);
this.buffer = Buffer.alloc(0);
this.push(this.buffer.slice(0, this.position));
this.buffer = Buffer.alloc(this.length);
cb();
}
};
Expand Down