mirror of
https://github.com/demostf/demo.js
synced 2026-06-04 00:54:14 +02:00
encoder for parser generator definitions
This commit is contained in:
parent
d3b893223b
commit
1e21b24763
3 changed files with 88 additions and 4 deletions
|
|
@ -1,18 +1,39 @@
|
|||
import * as assert from 'assert';
|
||||
import {make} from '../../../../Parser/Packet/ParserGenerator';
|
||||
import {BitStream} from 'bit-buffer';
|
||||
import {Packet} from '../../../../Data/Packet';
|
||||
|
||||
function getStream(data: string) {
|
||||
const buffer = new Buffer(data);
|
||||
return new BitStream(buffer);
|
||||
}
|
||||
|
||||
function assertEncoder(definition: string, data: any, length: number = 0) {
|
||||
const stream = new BitStream(new ArrayBuffer(64));
|
||||
const {parser, encoder} = make('packetName', definition);
|
||||
data.packetType = 'packetName';
|
||||
|
||||
encoder(data as Packet, stream);
|
||||
|
||||
const pos = stream.index;
|
||||
|
||||
if (length) {
|
||||
assert.equal(stream.index, length, 'Unexpected number of bits used for encoding');
|
||||
}
|
||||
|
||||
stream.index = 0;
|
||||
|
||||
const result = parser(stream);
|
||||
assert.deepEqual(data, result);
|
||||
assert.equal(pos, stream.index, 'Number of bits used for encoding and parsing not equal');
|
||||
}
|
||||
|
||||
function assertParser(definition: string, stream: BitStream, expected: any, length: number) {
|
||||
const {parser} = make('packetName', definition);
|
||||
expected.packetType = 'packetName';
|
||||
const start = stream.index;
|
||||
assert.deepEqual(expected, parser(stream));
|
||||
assert.equal(length, stream.index - start, 'Unexpected number of bits consumed from stream');
|
||||
assert.equal(stream.index - start, length, 'Unexpected number of bits consumed from stream');
|
||||
}
|
||||
|
||||
suite('Parser generator', () => {
|
||||
|
|
@ -83,4 +104,40 @@ suite('Parser generator', () => {
|
|||
|
||||
assertParser('foo{f32}', stream, {foo: 12.234233856201172}, 32);
|
||||
});
|
||||
|
||||
test('Encode fixed string', () => {
|
||||
assertEncoder('foo{s3}', {
|
||||
foo: 'bar'
|
||||
}, 3 * 8);
|
||||
});
|
||||
|
||||
test('Encode null terminated string', () => {
|
||||
assertEncoder('foo{s}', {
|
||||
foo: 'bar'
|
||||
}, 4 * 8);
|
||||
});
|
||||
|
||||
test('Encode booleans', () => {
|
||||
assertEncoder('foo{b}bar{b}', {
|
||||
foo: 1,
|
||||
bar: 0
|
||||
}, 2);
|
||||
});
|
||||
test('Encode integers', () => {
|
||||
assertEncoder('foo{u2}bar{12}', {
|
||||
foo: 3,
|
||||
bar: 7
|
||||
}, 2 + 12);
|
||||
});
|
||||
test('Encode variable length', () => {
|
||||
assertEncoder('foo{u2}bar{$foo}', {
|
||||
foo: 3,
|
||||
bar: 4
|
||||
}, 2 + 3);
|
||||
});
|
||||
test('Encode float', () => {
|
||||
assertEncoder('foo{f32}', {
|
||||
foo: 3.5
|
||||
}, 32);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue