Skip to content
Open
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
8 changes: 6 additions & 2 deletions src/datatypes/compiler-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,9 @@ return (ctx.${type})(val, buffer, offset)
}],
mapper: ['parametrizable', (compiler, mapper) => {
const mappings = JSON.stringify(swapMappings(mapper.mappings))
const code = 'return ' + compiler.callType(`${mappings}[value] || value`, mapper.type)
let code = `const mapped = ${mappings}[value]\n`
code += 'if (mapped === undefined) throw new Error(value + \' is not in the mappings value\')\n'
code += 'return ' + compiler.callType('mapped', mapper.type)
return compiler.wrapCode(code)
}]
},
Expand Down Expand Up @@ -211,7 +213,9 @@ return (ctx.${type})(val)
}],
mapper: ['parametrizable', (compiler, mapper) => {
const mappings = JSON.stringify(swapMappings(mapper.mappings))
const code = 'return ' + compiler.callType(`${mappings}[value] || value`, mapper.type)
let code = `const mapped = ${mappings}[value]\n`
code += 'if (mapped === undefined) throw new Error(value + \' is not in the mappings value\')\n'
code += 'return ' + compiler.callType('mapped', mapper.type)
return compiler.wrapCode(code)
}]
}
Expand Down
22 changes: 22 additions & 0 deletions test/misc.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,27 @@
/* eslint-env mocha */

const assert = require('assert')
const { ProtoDef } = require('../')
const { ProtoDefCompiler } = require('../').Compiler

it('example works', () => {
require('../example')
})

describe('mapper', () => {
const mapper = ['mapper', { type: 'varint', mappings: { '0x00': 'zero', '0x01': 'one' } }]
const proto = new ProtoDef()
proto.addType('name', mapper)
const compiler = new ProtoDefCompiler()
compiler.addTypesToCompile({ name: mapper })
const compiled = compiler.compileProtoDefSync()

for (const [label, p] of [['interpreted', proto], ['compiled', compiled]]) {
it(`writes a value mapped to 0 (${label})`, () => {
assert.deepStrictEqual(p.createPacketBuffer('name', 'zero'), Buffer.from([0]))
})
it(`throws on a value not in the mappings instead of writing it (${label})`, () => {
assert.throws(() => p.createPacketBuffer('name', 'nope'), /nope is not in the mappings value/)
})
}
})
Loading