keichi / binary-parser

A blazing-fast declarative parser builder for binary data
MIT License
857 stars 133 forks source link

Combining choice with array. #210

Closed blogwebpl closed 1 year ago

blogwebpl commented 1 year ago

It is possible to combining choice with array but I can find example. Can you give an example ?

keichi commented 1 year ago

Yes you can combine choices and arrays. Do you need an array of choices or a choice of arrays?

blogwebpl commented 1 year ago

I need array of choices.

keichi commented 1 year ago

Here's a quick example:

const Parser = require("binary-parser").Parser;

const parser = new Parser()
    .array("choices", {
        type: new Parser()
            .uint8("type")
            .choice("data", {
                tag: "type",
                choices: {
                    1: new Parser().uint8("a"),
                    2: new Parser().uint16("b"),
                    3: new Parser().uint32("c"),
                }
            }),
        length: 3
    });

const buf = Buffer.from("01030200040300000006", "hex");

console.dir(parser.parse(buf), {depth: null});

You can use any parser as an array element. Hope this helps.

blogwebpl commented 1 year ago

Thank you :)