Method to get the current offset in buffer when parsed
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
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++.
this pr is useful, will it to be merged?