Skip to content

Commit 9c64d23

Browse files
committed
Pass more context parameters to formatter and encoder options
1 parent 9285e9d commit 9c64d23

File tree

2 files changed

+14
-7
lines changed

2 files changed

+14
-7
lines changed

README.md

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -425,27 +425,30 @@ Usually used for debugging.
425425
These are common options that can be specified in all parsers.
426426

427427
- `formatter` - Function that transforms the parsed value into a more desired
428-
form.
428+
form. *formatter*(value, obj, buffer, offset) → *new value* \
429+
where `value` is the value to be formatted, `obj` is the current object being generated, `buffer` is the buffer currently beeing parsed and `offset` is the current offset in that buffer.
429430
```javascript
430431
var parser = new Parser().array("ipv4", {
431432
type: uint8,
432433
length: "4",
433-
formatter: function(arr) {
434+
formatter: function(arr, obj, buffer, offset) {
434435
return arr.join(".");
435436
}
436437
});
437438
```
438439

439440
- `encoder` - Function that transforms an object property into a more desired
440-
form for encoding. This is the opposite of the above `formatter` function.
441+
form for encoding. This is the opposite of the above `formatter` function. \
442+
*encoder*(value) → *new value* \
443+
where `value` is the value to be encoded (de-formatted) and `obj` is the object currently being encoded.
441444
```javascript
442445
var parser = new Parser().array("ipv4", {
443446
type: uint8,
444447
length: "4",
445-
formatter: function(arr) {
448+
formatter: function(arr, obj, buffer, offset) {
446449
return arr.join(".");
447450
},
448-
encoder: function(str) {
451+
encoder: function(str, obj) {
449452
return str.split(".");
450453
}
451454
});

lib/binary_parser.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1121,13 +1121,17 @@ Parser.prototype.generate_encodeNest = function(ctx) {
11211121

11221122
Parser.prototype.generateFormatter = function(ctx, varName, formatter) {
11231123
if (typeof formatter === "function") {
1124-
ctx.pushCode("{0} = ({1}).call(this, {0});", varName, formatter);
1124+
ctx.pushCode(
1125+
"{0} = ({1}).call(this, {0}, vars, buffer, offset);",
1126+
varName,
1127+
formatter
1128+
);
11251129
}
11261130
};
11271131

11281132
Parser.prototype.generateEncoder = function(ctx, varName, encoder) {
11291133
if (typeof encoder === "function") {
1130-
ctx.pushCode("{0} = ({1}).call(this, {0});", varName, encoder);
1134+
ctx.pushCode("{0} = ({1}).call(this, {0}, vars);", varName, encoder);
11311135
}
11321136
};
11331137

0 commit comments

Comments
 (0)