Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow for v8.serialize() to write to a target Uint8Array #55480

Open
mcollina opened this issue Oct 21, 2024 · 0 comments
Open

Allow for v8.serialize() to write to a target Uint8Array #55480

mcollina opened this issue Oct 21, 2024 · 0 comments
Labels
v8 module Issues and PRs related to the "v8" subsystem.

Comments

@mcollina
Copy link
Member

Consider this function that writes a given object to a SharedArrayBuffer, using v8.serialize():

function write (buffer, object, byteOffset = 0) {
  const data = serialize(object)

  if (buffer.byteLength < data.byteLength + 4 + byteOffset) {
    if (!buffer.growable) {
      throw new Error('Buffer is not growable')
    }
    /* c8 ignore next 2 */
    buffer.grow(data.byteLength + 4 + byteOffset)
  }
  const view = new DataView(buffer, byteOffset)
  view.setUint32(0, data.byteLength, true)
  new Uint8Array(buffer, byteOffset + 4).set(data)
}

This unfortunately causes a full copy of the object from the output of v8.serialize() into the target SharedArrayBuffer. If we could add a target, something like:

serialize(object, {
  buffer,
  offset,
  growIfNeeded: true
})

We could save a full copy of the buffer in this way.

If growing as needed is not feasible, we could do:

function write (object, buffer, offset) {
  try {
    serialize(object, { buffer, offset })
  } catch (err) {
    if (err.code === 'BUFFER_TOO_SMALL') {
      buffer = buffer.grow(err.neededSize)
      serialize(object, buffer, offset)
    } else {
      throw err
    }
  }
}
@RedYetiDev RedYetiDev added the v8 module Issues and PRs related to the "v8" subsystem. label Oct 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
v8 module Issues and PRs related to the "v8" subsystem.
Projects
None yet
Development

No branches or pull requests

2 participants