Skip to content

Commit 16a2ffc

Browse files
razvanalexdbaileychess
authored andcommitted
[TS/JS] Create byte vectors (google#8185)
* Add createByteVector and use set in createString * Add test for CreateByteVector --------- Co-authored-by: Derek Bailey <[email protected]>
1 parent 32d1783 commit 16a2ffc

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

tests/ts/JavaScriptTest.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ function main() {
4848
testNullStrings();
4949
testSharedStrings();
5050
testVectorOfStructs();
51+
testCreateByteVector();
5152

5253
console.log('FlatBuffers test: completed successfully');
5354
}
@@ -477,4 +478,20 @@ function testVectorOfStructs() {
477478
assert.strictEqual(decodedMonster.test4[1].b, 4);
478479
}
479480

481+
function testCreateByteVector() {
482+
const data = Uint8Array.from([1, 2, 3, 4, 5]);
483+
484+
const builder = new flatbuffers.Builder();
485+
const required = builder.createString("required");
486+
const offset = builder.createByteVector(data);
487+
488+
Monster.startMonster(builder);
489+
Monster.addName(builder, required);
490+
Monster.addInventory(builder, offset)
491+
builder.finish(Monster.endMonster(builder));
492+
493+
let decodedMonster = Monster.getRootAsMonster(builder.dataBuffer());
494+
assert.deepEqual(decodedMonster.inventoryArray(), data);
495+
}
496+
480497
main();

ts/builder.ts

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -539,9 +539,24 @@ export class Builder {
539539
this.addInt8(0);
540540
this.startVector(1, utf8.length, 1);
541541
this.bb.setPosition(this.space -= utf8.length);
542-
for (let i = 0, offset = this.space, bytes = this.bb.bytes(); i < utf8.length; i++) {
543-
bytes[offset++] = utf8[i];
542+
this.bb.bytes().set(utf8, this.space);
543+
return this.endVector();
544+
}
545+
546+
/**
547+
* Create a byte vector.
548+
*
549+
* @param v The bytes to add
550+
* @returns The offset in the buffer where the byte vector starts
551+
*/
552+
createByteVector(v: Uint8Array | null | undefined): Offset {
553+
if (v === null || v === undefined) {
554+
return 0;
544555
}
556+
557+
this.startVector(1, v.length, 1);
558+
this.bb.setPosition(this.space -= v.length);
559+
this.bb.bytes().set(v, this.space);
545560
return this.endVector();
546561
}
547562

0 commit comments

Comments
 (0)