{"id":13622727,"url":"https://github.com/GoogleChromeLabs/buffer-backed-object","last_synced_at":"2025-04-15T09:33:44.245Z","repository":{"id":38244288,"uuid":"253877145","full_name":"GoogleChromeLabs/buffer-backed-object","owner":"GoogleChromeLabs","description":"Buffer-backed objects in JavaScript.","archived":false,"fork":false,"pushed_at":"2024-09-27T05:29:11.000Z","size":782,"stargazers_count":380,"open_issues_count":12,"forks_count":14,"subscribers_count":7,"default_branch":"main","last_synced_at":"2024-10-02T02:24:48.618Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"https://npm.im/buffer-backed-object","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/GoogleChromeLabs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":"CODEOWNERS","security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2020-04-07T18:19:59.000Z","updated_at":"2024-09-22T09:58:24.000Z","dependencies_parsed_at":"2024-06-19T04:00:38.965Z","dependency_job_id":null,"html_url":"https://github.com/GoogleChromeLabs/buffer-backed-object","commit_stats":{"total_commits":55,"total_committers":7,"mean_commits":7.857142857142857,"dds":0.4,"last_synced_commit":"fc7e0bab05795ab4a9f4977bbd285fdae27051f7"},"previous_names":[],"tags_count":11,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoogleChromeLabs%2Fbuffer-backed-object","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoogleChromeLabs%2Fbuffer-backed-object/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoogleChromeLabs%2Fbuffer-backed-object/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/GoogleChromeLabs%2Fbuffer-backed-object/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/GoogleChromeLabs","download_url":"https://codeload.github.com/GoogleChromeLabs/buffer-backed-object/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":223668367,"owners_count":17182914,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-01T21:01:23.385Z","updated_at":"2025-04-15T09:33:44.225Z","avatar_url":"https://github.com/GoogleChromeLabs.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# `BufferBackedObject`\n\n**`BufferBackedObject` creates objects that are backed by an `ArrayBuffer`**. It takes a schema definition and de/serializes data on-demand using [`DataView`][dataview] under the hood. The goal is to make [`ArrayBuffer`][arraybuffer]s more convenient to use.\n\n```\nnpm i -S buffer-backed-object\n```\n\n## Why?\n\n### Web Workers\n\nWhen using [Web Workers], the performance of `postMessage()` (or the [structured clone algorithm][structured clone] to be exact) is often a concern. While [`postMessage()` is a lot faster than most people give it credit for][is postmessage slow], it can still occasionally be a bottle-neck, especially with bigger payloads. [`ArrayBuffer`][arraybuffer] and their [views][arraybufferview] are incredibly quick to clone (or can even be [transferred][transferable]), but getting data in and out of `ArrayBuffer`s can be cumbersome. `BufferBackedObject` makes this easy by giving you a (seemingly) normal JavaScript object that reads and write values from the `ArrayBuffer` on demand. This means that the serialization \u0026 deserialization costs are deferred to the point of access rather than paid upfront, as it is the case with `postMessage()`.\n\n### WebGL\n\n[WebGL Buffers][webgl buffer] can store multiple attributes per vertex using [`vertexAttribPointer()`][vertexattribpointer]. These attributes can be a 3D position, but also other additional data like a normal vector, a color or a texture ID. The underlying buffer contains all the attributes for all the vertices in an interleaved format, which can make manipulating that data quite hard. With `ArrayOfBufferBackedObjects` you can manipulate each vertex individually. Additionally, `ArrayOfBufferBackedObjects` is populated lazily (see more below), allowing you to handle big arrays of vertices more efficiently.\n\n### WebGPU\n\nSimilary, you can define structs in WGLS and read from/write to GPU memory buffers. With `BufferBackedObject` or `ArrayOfBufferBackedObjects`, you can manipulate those structs from JavaScript more easily and efficiently.\n\n## Example\n\n```js\nimport * as BBO from \"buffer-backed-object\";\n\nconst buffer = new ArrayBuffer(100);\nconst view = BBO.BufferBackedObject(buffer, {\n  id: BBO.Uint16({ endianness: \"big\" }),\n  position: BBO.NestedBufferBackedObject({\n    x: BBO.Float32(),\n    y: BBO.Float32(),\n    z: BBO.Float32(),\n  }),\n  normal: BBO.NestedBufferBackedObject({\n    x: BBO.Float32(),\n    y: BBO.Float32(),\n    z: BBO.Float32(),\n  }),\n  textureId: BBO.Uint8(),\n});\n\nview.id = 3;\nconsole.log(new Uint8Array(buffer));\n// logs: Uint8Array(100) [3, 0, ...]\nconsole.log(JSON.stringify(view));\n// logs: {\"id\": 3, \"position\": {\"x\": 0, ...}, ...}\n```\n\n`ArrayOfBufferBackedObjects` interprets the given `ArrayBuffer` as an _array_ of objects with the given schema:\n\n```js\nimport * as BBO from \"buffer-backed-object\";\n\nconst buffer = new ArrayBuffer(100);\nconst view = BBO.ArrayOfBufferBackedObjects(buffer, {\n  id: BBO.Uint16({ endianness: \"big\" }),\n  position: BBO.NestedBufferBackedObject({\n    x: BBO.Float32(),\n    y: BBO.Float32(),\n    z: BBO.Float32(),\n  }),\n  normal: BBO.NestedBufferBackedObject({\n    x: BBO.Float32(),\n    y: BBO.Float32(),\n    z: BBO.Float32(),\n  }),\n  textureId: BBO.Uint8(),\n});\n\n// The struct takes up a total of 27 bytes, so\n// 3 structs can fit into a 100 byte `ArrayBuffer`.\nconsole.log(view.length);\n// logs: 3\n\nview[0].id = 1000;\nview[1].id = 1001;\nview[2].id = 1002;\nconsole.log(new Uint8Array(buffer));\n// logs: Uint8Array(100) [232, 3, ...]\nconsole.log(JSON.stringify(view));\n// logs: [{\"id\": 1000, ...}, {\"id\": 1001}, ...]\n```\n\n## API\n\nThe module has the following exports:\n\n### `function BufferBackedObject(buffer, descriptors, {byteOffset = 0})`\n\nThe key/value pairs in the `descriptors` object must be declared in the same order as they are laid out in the buffer. The returned object has getters and setters for each of `descriptors` properties and de/serializes them `buffer`, starting at the given `byteOffset`.\n\n### `function ArrayOfBufferBackedObjects(buffer, descriptors, {byteOffset = 0, length = 0})`\n\nLike `BufferBackedObject`, but returns an _array_ of `BufferBackedObject`s. If `length` is 0, as much of the buffer is used as possible. The array is populated lazily under the hood for performance purposes. That is, the individual `BufferBackedObject`s will only be created when their index is accessed.\n\n### `function structSize(descriptors)`\n\nReturns the number of bytes required to store a value with the schema outlined by `descriptors`.\n\n### Descriptors\n\nThe following descriptor types are available as individually exported functions\n\n- `function reserved(numBytes)`: A number of unused bytes. This field will now show up in the object.\n- `function Int8()`: An 8-bit signed integer\n- `function Uint8()`: An 8-bit unsigned integer\n- `function Int16({align = 2, endianness = 'little'})`: An 16-bit signed integer\n- `function Uint16({align = 2, endianness = 'little'})`: An 16-bit unsigned integer\n- `function Int32({align = 4, endianness = 'little'})`: An 32-bit signed integer\n- `function Uint32({align = 4, endianness = 'little'})`: An 32-bit unsigned integer\n- `function BigInt64({align = 8, endianness = 'little'})`: An 64-bit signed [`BigInt`][bigint]\n- `function BigUint64({align = 8, endianness = 'little'})`: An 64-bit unsigned [`BigInt`][bigint]\n- `function Float32({align = 4, endianness = 'little'})`: An 32-bit IEEE754 float\n- `function Float64({align = 8, endianness = 'little'})`: An 64-bit IEEE754 float (“double”)\n- `function UTF8String(maxBytes)`: A UTF-8 encoded string with the given maximum number of bytes. Trailing NULL bytes will be trimmed after decoding.\n- `function NestedBufferBackedObject(descriptors)`: A nested `BufferBackedObject` with the given descriptors\n- `function NestedArrayOfBufferBackedObjects(numItems, descriptors)`: A nested `ArrayOfBufferBackedObjects` of length `numItems` with the given descriptors\n\n## Defining your own descriptor types\n\nAll the descriptor functions return an object with the following structure:\n\n```js\n{\n  align?: 1, // Required aligment\n  size: 4, // Size required by the type\n  get(dataView, byteOffset) {\n    // Decode the value at byteOffset using\n    // `dataView` or `dataView.buffer` and\n    // return it.\n  },\n  set(dataView, byteOffset, value) {\n    // Store `value` at `byteOffset` using\n    // `dataView` or `dataView.buffer`.\n  }\n}\n```\n\n---\n\nLicense Apache-2.0\n\n[dataview]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView\n[arraybuffer]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer\n[web workers]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API\n[structured clone]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm\n[is postmessage slow]: https://surma.dev/things/is-postmessage-slow/\n[arraybufferview]: https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView\n[transferable]: https://developer.mozilla.org/en-US/docs/Web/API/Transferable\n[bigint]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt\n[webgl buffer]: https://developer.mozilla.org/en-US/docs/Web/API/WebGLBuffer\n[vertexattribpointer]: https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/vertexAttribPointer\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FGoogleChromeLabs%2Fbuffer-backed-object","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FGoogleChromeLabs%2Fbuffer-backed-object","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FGoogleChromeLabs%2Fbuffer-backed-object/lists"}