2024-06-10 22:42:30 -05:00
|
|
|
|
import {expect, test} from 'vitest';
|
|
|
|
|
|
|
|
|
|
import Schema from './schema.js';
|
|
|
|
|
|
|
|
|
|
test('validates a schema', () => {
|
|
|
|
|
expect(() => {
|
|
|
|
|
new Schema({test: 'unknown'})
|
|
|
|
|
})
|
|
|
|
|
.to.throw();
|
|
|
|
|
expect(() => {
|
|
|
|
|
new Schema({test: 'unknown'})
|
|
|
|
|
})
|
|
|
|
|
.to.throw();
|
|
|
|
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
test('calculates the size of an instance', () => {
|
2024-06-11 21:00:03 -05:00
|
|
|
|
expect(
|
|
|
|
|
(new Schema({foo: 'uint8', bar: 'uint32'}))
|
|
|
|
|
.sizeOf({foo: 69, bar: 420})
|
|
|
|
|
)
|
2024-06-10 22:42:30 -05:00
|
|
|
|
.to.equal(5);
|
2024-06-11 21:00:03 -05:00
|
|
|
|
expect(
|
|
|
|
|
(new Schema({foo: 'string'}))
|
|
|
|
|
.sizeOf({foo: 'hi'})
|
|
|
|
|
)
|
2024-06-10 22:42:30 -05:00
|
|
|
|
.to.equal(4 + (new TextEncoder().encode('hi')).length);
|
|
|
|
|
});
|
2024-06-11 21:00:03 -05:00
|
|
|
|
|
|
|
|
|
test('can encode and decode', () => {
|
|
|
|
|
const entries = [
|
|
|
|
|
['uint8', 255],
|
|
|
|
|
['int8', -128],
|
|
|
|
|
['int8', 127],
|
|
|
|
|
['uint16', 65535],
|
|
|
|
|
['int16', -32768],
|
|
|
|
|
['int16', 32767],
|
|
|
|
|
['uint32', 4294967295],
|
|
|
|
|
['int32', -2147483648],
|
|
|
|
|
['int32', 2147483647],
|
|
|
|
|
['uint64', 18446744073709551615n],
|
|
|
|
|
['int64', -9223372036854775808n],
|
|
|
|
|
['int64', 9223372036854775807n],
|
|
|
|
|
['float32', 0.5],
|
|
|
|
|
['float64', 1.234],
|
|
|
|
|
['string', 'hello world'],
|
|
|
|
|
['string', 'α'],
|
|
|
|
|
];
|
|
|
|
|
const specification = entries.reduce((r, [type]) => ({...r, [Object.keys(r).length]: type}), {});
|
|
|
|
|
const data = entries.reduce((r, [, value]) => ({...r, [Object.keys(r).length]: value}), {});
|
|
|
|
|
const schema = new Schema(specification);
|
|
|
|
|
const view = new DataView(new ArrayBuffer(schema.sizeOf(data)));
|
|
|
|
|
schema.serialize(data, view);
|
|
|
|
|
const result = {};
|
|
|
|
|
schema.deserialize(result, view);
|
|
|
|
|
expect(data)
|
|
|
|
|
.to.deep.equal(result);
|
|
|
|
|
});
|