From f92025a0d4fe54e6cda0d3b389bed23e8ebfd9ba Mon Sep 17 00:00:00 2001 From: U9G Date: Thu, 8 Oct 2026 16:25:10 -0400 Subject: [PATCH] Compiled mapper: write a raw integer not in the mappings through The compiled read returns the raw id for a value not in the mappings, so a proxy that re-encodes what it reads (e.g. bedrock-protocol Relay) has to be able to write that integer back. Since #176 the write threw on it. Pass raw integers through to the underlying type; unmapped names and undefined still throw. --- src/datatypes/compiler-utils.js | 14 ++++++++++---- test/misc.js | 6 ++++++ 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/datatypes/compiler-utils.js b/src/datatypes/compiler-utils.js index 6625a51..c74afec 100644 --- a/src/datatypes/compiler-utils.js +++ b/src/datatypes/compiler-utils.js @@ -160,8 +160,11 @@ return (ctx.${type})(val, buffer, offset) }], mapper: ['parametrizable', (compiler, mapper) => { const mappings = JSON.stringify(swapMappings(mapper.mappings)) - let code = `const mapped = ${mappings}[value]\n` - code += 'if (mapped === undefined) throw new Error(value + \' is not in the mappings value\')\n' + let code = `let mapped = ${mappings}[value]\n` + code += 'if (mapped === undefined) {\n' + code += ' if (typeof value !== \'number\') throw new Error(value + \' is not in the mappings value\')\n' + code += ' mapped = value\n' + code += '}\n' code += 'return ' + compiler.callType('mapped', mapper.type) return compiler.wrapCode(code) }] @@ -215,8 +218,11 @@ return (ctx.${type})(val) }], mapper: ['parametrizable', (compiler, mapper) => { const mappings = JSON.stringify(swapMappings(mapper.mappings)) - let code = `const mapped = ${mappings}[value]\n` - code += 'if (mapped === undefined) throw new Error(value + \' is not in the mappings value\')\n' + let code = `let mapped = ${mappings}[value]\n` + code += 'if (mapped === undefined) {\n' + code += ' if (typeof value !== \'number\') throw new Error(value + \' is not in the mappings value\')\n' + code += ' mapped = value\n' + code += '}\n' code += 'return ' + compiler.callType('mapped', mapper.type) return compiler.wrapCode(code) }] diff --git a/test/misc.js b/test/misc.js index 6877ba4..3ae1325 100644 --- a/test/misc.js +++ b/test/misc.js @@ -24,6 +24,12 @@ describe('mapper', () => { assert.throws(() => p.createPacketBuffer('name', 'nope'), /nope is not in the mappings value/) }) } + + // The compiled read returns the raw id for a value not in the mappings, so writing it back must work + it('writes a raw integer not in the mappings (compiled)', () => { + assert.deepStrictEqual(compiled.createPacketBuffer('name', 5), Buffer.from([5])) + assert.strictEqual(compiled.parsePacketBuffer('name', Buffer.from([5])).data, 5) + }) }) describe('bitflags', () => {