Skip to content
Closed
Show file tree
Hide file tree
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
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,30 @@ current object. `options` is an object which can have the following keys:
### skip(length)
Skip parsing for `length` bytes.

### saveOffset(name, options)
Save the current buffer offset as key `name`. This function is only useful when called after another function which would advance the internal buffer offset.

```javascript
var parser = new Parser()
// this call advances the buffer offset by
// a variable (i.e. unknown to us) number of bytes
.string('name', {
zeroTerminated: true
})
// this variable points to an absolute position
// in the buffer
.uint32('seekOffset')
// now, save the "current" offset in the stream
// as the variable "currentOffset"
.saveOffset('currentOffset')
// finally, use the saved offset to figure out
// how many bytes we need to skip
.skip(function() {
return this.seekOffset - this.currentOffset;
})
... // the parser would continue here
```

### endianess(endianess)
Define what endianess to use in this parser. `endianess` can be either
`"little"` or `"big"`. The default endianess of `Parser` is set to big-endian.
Expand Down
14 changes: 12 additions & 2 deletions lib/binary_parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,8 @@ var SPECIAL_TYPES = {
Skip: null,
Choice: null,
Nest: null,
Bit: null
Bit: null,
SaveOffset: null
};

var aliasRegistry = {};
Expand Down Expand Up @@ -116,6 +117,10 @@ Parser.prototype.skip = function(length, options) {
return this.setNextParser("skip", "", { length: length });
};

Parser.prototype.saveOffset = function(varName, options) {
return this.setNextParser("saveoffset", varName, options);
};

Parser.prototype.string = function(varName, options) {
if (!options.zeroTerminated && !options.length && !options.greedy) {
throw new Error(
Expand Down Expand Up @@ -359,7 +364,7 @@ Parser.prototype.sizeOf = function() {
// if this is a nested parser
} else if (this.type === "Nest") {
size = this.options.type.sizeOf();
} else if (!this.type) {
} else if (this.type === "SaveOffset" || !this.type) {
size = 0;
}

Expand Down Expand Up @@ -528,6 +533,11 @@ Parser.prototype.generateSkip = function(ctx) {
ctx.pushCode("offset += {0};", length);
};

Parser.prototype.generateSaveOffset = function(ctx) {
var name = ctx.generateVariable(this.varName);
ctx.pushCode("{0} = offset;", name);
};

Parser.prototype.generateString = function(ctx) {
var name = ctx.generateVariable(this.varName);
var start = ctx.generateTmpVariable();
Expand Down
Loading