GoogleChromeLabs / buffer-backed-object

Buffer-backed objects in JavaScript.
https://npm.im/buffer-backed-object
Apache License 2.0
376 stars 14 forks source link

BBO.NestedBufferBackedObject doesn't work at all (or I am not understanding it correctly?) #43

Open webhype opened 11 months ago

webhype commented 11 months ago

Consider the below sample code to reproduce the problem.

When I populate ONLY "record 1" (as opposed to "record 0") of the arrayView, and then query the uninitialized "virgin" nested object that should belong to record 0, then the expected result would be an empty string or undefined or null or something to that effect.

However, it outputs the nested object from index 1; in the below code it prints "hello, this is record 1". When I "flatten" the hierarchy and avoid NestedBufferBackedObject, then an index of 0 returns only what pertains to record 0 and not record 1 (i.e. expected behavior).

import * as BBO from "buffer-backed-object";

const ARRAY_STRUCT = {
    id: BBO.Uint32({endianness: "big"}),
    nestedObject: BBO.NestedBufferBackedObject({
        nestedStr: BBO.UTF8String(80),
    }),
}

const size = 1000;
const arrayBuf = new SharedArrayBuffer(size * BBO.structSize(ARRAY_STRUCT));
const arrayView = BBO.ArrayOfBufferBackedObjects(arrayBuf, ARRAY_STRUCT);

let bbo1 = arrayView[1];    // <== populating record 1, not 0!
bbo1.id = 123;
bbo1.nestedObject.nestedStr = "hello, this is record 1";

let bbo0 = arrayView[0];    // <== retrieving record 0, not 1!
// Expected result: Empty string
// Actual result: hello, this is record 1
console.log(bbo0.nestedObject.nestedStr);