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

Add a new Int node to parse intBE, intLE, uIntBE and uIntLE values. #1

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,22 @@ export class Builder {
return new node.Match(name);
}

public intBE(name: string, bytes: number): node.Int {
return new node.Int(name, bytes, true, false);
}

public intLE(name: string, bytes: number): node.Int {
return new node.Int(name, bytes, true, true);
}

public uIntBE(name: string, bytes: number): node.Int {
return new node.Int(name, bytes, false, false);
}

public uIntLE(name: string, bytes: number): node.Int {
return new node.Int(name, bytes, false, true);
}

/**
* Create terminal error node. Returns error code to user, and sets reason
* in the parser's state object.
Expand Down
1 change: 1 addition & 0 deletions src/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ export { Match } from './match';
export { Pause } from './pause';
export { SpanStart } from './span-start';
export { SpanEnd } from './span-end';
export { Int } from './int';
28 changes: 28 additions & 0 deletions src/node/int.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import * as assert from 'assert';

import { Node } from './base';

function buildName(field: string, bytes: number, signed: boolean, littleEndian: boolean) {
const type = signed ? 'int' : 'uint';
const bits = bytes * 8;
const endianness = littleEndian ? 'le' : 'be';

if (bytes > 1) {
return `${field}_${type}_${bits}_${endianness}`;
} else {
return `${field}_${type}_${bits}`;
}
}

export class Int extends Node {
/**
* @param field State's property name
*/
constructor(public readonly field: string, public readonly bytes: number, public readonly signed: boolean, public readonly littleEndian: boolean) {
super(buildName(field, bytes, signed, littleEndian));

if (/^_/.test(field)) {
throw new Error(`Can't use internal field in \`Int\`: "${field}"`);
}
}
}