Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit

Permalink
[TS/JS] Create byte vectors (#8185)
Browse files Browse the repository at this point in the history
* Add createByteVector and use set in createString

* Add test for CreateByteVector

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
  • Loading branch information
razvanalex and dbaileychess authored Dec 19, 2023
1 parent 70c8292 commit c0d1699
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
17 changes: 17 additions & 0 deletions tests/ts/JavaScriptTest.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ function main() {
testNullStrings();
testSharedStrings();
testVectorOfStructs();
testCreateByteVector();

console.log('FlatBuffers test: completed successfully');
}
Expand Down Expand Up @@ -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();
19 changes: 17 additions & 2 deletions ts/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}

Expand Down

0 comments on commit c0d1699

Please sign in to comment.