[TS/JS] Create byte vectors (#8185)

* Add createByteVector and use set in createString

* Add test for CreateByteVector

---------

Co-authored-by: Derek Bailey <derekbailey@google.com>
This commit is contained in:
razvanalex 2023-12-19 08:42:21 +02:00 committed by GitHub
parent 70c8292c29
commit c0d16995a4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 2 deletions

View File

@ -48,6 +48,7 @@ function main() {
testNullStrings(); testNullStrings();
testSharedStrings(); testSharedStrings();
testVectorOfStructs(); testVectorOfStructs();
testCreateByteVector();
console.log('FlatBuffers test: completed successfully'); console.log('FlatBuffers test: completed successfully');
} }
@ -477,4 +478,20 @@ function testVectorOfStructs() {
assert.strictEqual(decodedMonster.test4[1].b, 4); 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(); main();

View File

@ -539,9 +539,24 @@ export class Builder {
this.addInt8(0); this.addInt8(0);
this.startVector(1, utf8.length, 1); this.startVector(1, utf8.length, 1);
this.bb.setPosition(this.space -= utf8.length); this.bb.setPosition(this.space -= utf8.length);
for (let i = 0, offset = this.space, bytes = this.bb.bytes(); i < utf8.length; i++) { this.bb.bytes().set(utf8, this.space);
bytes[offset++] = utf8[i]; 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(); return this.endVector();
} }