Skip to content

Commit

Permalink
Added string parser the capabilities to strip null in order to correctly
Browse files Browse the repository at this point in the history
read null padded string
  • Loading branch information
Maxime Carey committed Dec 8, 2014
1 parent 7f2ff1f commit 3f2d212
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,11 @@ with an alphabet. `options` is an object; following options are available:

- `encoding` - (Optional, defaults to `utf8`) Specify which encoding to use. `'utf8'`, `'ascii'`, `'hex'` and else
are valid. See [`Buffer.toString`](http://nodejs.org/api/buffer.html#buffer_buf_tostring_encoding_start_end) for more info.
- `length ` - (Required) Length of the string. Can be a number, string or a function.
- `length ` - (Optional) Length of the string. Can be a number, string or a function.
Use number for statically sized arrays, string to reference another variable and
function to do some calculation.
- `zeroTerminated` - (Optional, defaults to `false`) If true, then this parser reads until it reaches zero.
- `stripNull` - (Optional, must be used with `length`) If true, then strip null characters from end of the string

### buffer(name [,options])
Parse bytes as a buffer. `name` should consist only of alpha numeric characters and start
Expand Down
23 changes: 14 additions & 9 deletions lib/binary_parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,20 @@ Parser.prototype.generateSkip = function(ctx) {
};

Parser.prototype.generateString = function(ctx) {
if (this.options.zeroTerminated) {
if(this.options.length) {
var name = ctx.generateVariable(this.varName);
ctx.pushCode('{0} = buffer.toString(\'{1}\', offset, offset + {2});',
name,
this.options.encoding,
ctx.generateOption(this.options.length)
);
if(this.options.stripNull)
{
ctx.pushCode('{0} = {0}.replace(/\0/g, \'\')', name);
}
ctx.pushCode('offset += {0};', ctx.generateOption(this.options.length));
}
else {
var start = ctx.generateTmpVariable();

ctx.pushCode('var {0} = offset;', start);
Expand All @@ -403,14 +416,6 @@ Parser.prototype.generateString = function(ctx) {
start
);
}
else {
ctx.pushCode('{0} = buffer.toString(\'{1}\', offset, offset + {2});',
ctx.generateVariable(this.varName),
this.options.encoding,
ctx.generateOption(this.options.length)
);
ctx.pushCode('offset += {0};', ctx.generateOption(this.options.length));
}
};

Parser.prototype.generateBuffer = function(ctx) {
Expand Down

0 comments on commit 3f2d212

Please sign in to comment.