Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamically Determine the Length of value Based on the flags Bitmask #66

Open
jiawei14755 opened this issue Nov 9, 2024 · 0 comments
Open

Comments

@jiawei14755
Copy link

Description

When parsing/serializing a buffer, I need to dynamically determine the length of the value field in a structure based on certain bits in the flags bitmask. For example:

  • If a specific bit (e.g., 0x08) is set in flags, parse value as uint8
  • Otherwise, parse value as uint16

Current Code Example

Currently, I’m using the restructure library with the following code:

const r = require('restructure');

const uint8 = new r.Struct({
    flags: r.uint8,
    value: r.uint8
});

const uint16 = new r.Struct({
    flags: r.uint8,
    value: r.uint16,
});

const buffer = Buffer.from([0x08, 0x34, 0x12]);
let flags = buffer.readUInt8();

if (flags & 0x8) {
    console.log(uint8.fromBuffer(buffer));
} else {
    console.log(uint16.fromBuffer(buffer));
}

Problem

This approach is limited since it requires manually determining the structure type based on flags. I would prefer a more dynamic way to define this directly within the restructure structure, allowing flags to control the size of value without extra conditionals.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant