From c0d16995a4f0a748a89ae72cc321dce2016be2c1 Mon Sep 17 00:00:00 2001 From: razvanalex Date: Tue, 19 Dec 2023 08:42:21 +0200 Subject: [PATCH] [TS/JS] Create byte vectors (#8185) * Add createByteVector and use set in createString * Add test for CreateByteVector --------- Co-authored-by: Derek Bailey --- tests/ts/JavaScriptTest.js | 17 +++++++++++++++++ ts/builder.ts | 19 +++++++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/tests/ts/JavaScriptTest.js b/tests/ts/JavaScriptTest.js index b76dd2ed5..1226e2e5d 100644 --- a/tests/ts/JavaScriptTest.js +++ b/tests/ts/JavaScriptTest.js @@ -48,6 +48,7 @@ function main() { testNullStrings(); testSharedStrings(); testVectorOfStructs(); + testCreateByteVector(); console.log('FlatBuffers test: completed successfully'); } @@ -477,4 +478,20 @@ function testVectorOfStructs() { assert.strictEqual(decodedMonster.test4[1].b, 4); } +function testCreateByteVector() { + const data = Uint8Array.from([1, 2, 3, 4, 5]); + + const builder = new flatbuffers.Builder(); + const required = builder.createString("required"); + const offset = builder.createByteVector(data); + + Monster.startMonster(builder); + Monster.addName(builder, required); + Monster.addInventory(builder, offset) + builder.finish(Monster.endMonster(builder)); + + let decodedMonster = Monster.getRootAsMonster(builder.dataBuffer()); + assert.deepEqual(decodedMonster.inventoryArray(), data); +} + main(); diff --git a/ts/builder.ts b/ts/builder.ts index c37929513..f7f69cfec 100644 --- a/ts/builder.ts +++ b/ts/builder.ts @@ -539,9 +539,24 @@ export class Builder { this.addInt8(0); this.startVector(1, utf8.length, 1); this.bb.setPosition(this.space -= utf8.length); - for (let i = 0, offset = this.space, bytes = this.bb.bytes(); i < utf8.length; i++) { - bytes[offset++] = utf8[i]; + this.bb.bytes().set(utf8, this.space); + return this.endVector(); + } + + /** + * Create a byte vector. + * + * @param v The bytes to add + * @returns The offset in the buffer where the byte vector starts + */ + createByteVector(v: Uint8Array | null | undefined): Offset { + if (v === null || v === undefined) { + return 0; } + + this.startVector(1, v.length, 1); + this.bb.setPosition(this.space -= v.length); + this.bb.bytes().set(v, this.space); return this.endVector(); }