Skip to content

Commit 99da317

Browse files
authored
Merge pull request #164 from abductedPlatypus/master
Add wrapper to transform data before further parsing
2 parents c55625b + 843bff9 commit 99da317

File tree

5 files changed

+313
-2507
lines changed

5 files changed

+313
-2507
lines changed

README.md

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -428,6 +428,49 @@ var buffer = Buffer.from([2, /* left */ 1, 1, 0, /* right */ 0]);
428428
parser.parse(buffer);
429429
```
430430

431+
### wrapped(name[, options])
432+
Read data then wrap it by transforming it by a function for further parsing.
433+
It works similarly to a buffer where it reads a block of data. But instead of returning the buffer it
434+
will pass it on to a parser for further processing.
435+
- `wrapper` - (Required) A function taking a buffer and returning a buffer (`(x: Buffer | Uint8Array ) => Buffer | Uint8Array`)
436+
transforming the buffer into a buffer expected by `type`.
437+
- `type` - (Required) A `Parser` object to parse the result of wrapper.
438+
- `length ` - (either `length` or `readUntil` is required) Length of the
439+
buffer. Can be a number, string or a function. Use number for statically
440+
sized buffers, string to reference another variable and function to do some
441+
calculation.
442+
- `readUntil` - (either `length` or `readUntil` is required) If `"eof"`, then
443+
this parser will read till it reaches the end of the `Buffer`/`Uint8Array`
444+
object. If it is a function, this parser will read the buffer until the
445+
function returns true.
446+
447+
```javascript
448+
const zlib = require('zlib');
449+
// A parser to run on the data returned by the wrapper
450+
var textParser = Parser.start()
451+
.string('text', {
452+
zeroTerminated: true,
453+
});
454+
455+
var mainParser = Parser.start()
456+
// Read length of the data to wrap
457+
.uint32le('length')
458+
// Read wrapped data
459+
.wrapped('wrappedData', {
460+
// Indicate how much data to read, like buffer()
461+
length: 'length',
462+
// Define function to pre-process the data buffer
463+
wrapper: function (buffer) {
464+
// E.g. decompress data and return it for further parsing
465+
return zlib.inflateRawSync(buffer);
466+
},
467+
// The parser to run the dec
468+
type: textParser,
469+
});
470+
mainParser.parse(buffer);
471+
```
472+
473+
431474
### compile()
432475
Compile this parser on-the-fly and cache its result. Usually, there is no need
433476
to call this method directly, since it's called when `parse(buffer)` is

0 commit comments

Comments
 (0)