Skip to content

Conversation

Ericbla
Copy link
Contributor

@Ericbla Ericbla commented Jan 20, 2018

Hello,

Whereas the un-documented sizeOf() method allows to get the size of what a static parser will consume.

Here is an implementation of a new getLastOffset() method that returns the effective size of parsed data from input buffer.

One possible usage for this method is to partially parse binary data from a buffer and then continue parsing starting where the last parse() stopped.

var parser = Parser.start()
   .uint8("b1")
   .uint8("b2");

var buffer = Buffer.from([1, 2, 3, 4, 5]);

parser.parse(buffer);  // { b1: 1, b2: 2 }
parser.getLastOffset(); // 2
parser.parse(buffer.slice(parser.getLastOffset())); //  { b1: 3, b2: 4 }

The previous example could be done using the sizeOf() method, but when using real life parser (with zeroTerminated string or using function as length option), this is the only way to determine where the parse(buffer) method has stopped.

I have also added some unit tests for this new method and updated the Readme.md

--
Eric

@Simran-B
Copy link
Contributor

I guess this could also be handy in skip() to align e.g. to multiples of 8 bytes? Padding is quite common in data structures like you get from C++.

@zzswang
Copy link

zzswang commented Jun 10, 2018

this pr is useful, will it to be merged?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants