Skip to content

Fix byte count in NodeAnyTypedArray.withUnsafeMutableRawBytes#60

Open
liautaud wants to merge 1 commit into
kabiroberai:mainfrom
liautaud:fix/typedarray-bytecount
Open

Fix byte count in NodeAnyTypedArray.withUnsafeMutableRawBytes#60
liautaud wants to merge 1 commit into
kabiroberai:mainfrom
liautaud:fix/typedarray-bytecount

Conversation

@liautaud
Copy link
Copy Markdown

Summary

NodeAnyTypedArray.withUnsafeMutableRawBytes currently passes the length value returned by napi_get_typedarray_info straight into UnsafeMutableRawBufferPointer(start:count:). Per the Node-API docs, that value is the element count of the typed array, not its byte count. The two only coincide for Int8 / UInt8 / Uint8Clamped arrays.

For every other typed-array kind, the returned raw buffer is silently truncated. This is particularly visible through NodeTypedArray<Element>.withUnsafeMutableBytes, which calls bindMemory(to: Element.self) on the returned raw buffer: the resulting UnsafeMutableBufferPointer<Element> reports a count divided by MemoryLayout<Element>.size, so callers only see a fraction of the actual elements (and any reads/writes beyond that fraction are silently skipped).

Fix

  • Query the typed-array kind from napi_get_typedarray_info (instead of passing nil for the type out-parameter).
  • Multiply the returned element count by the per-element byte size to get the real byte count.
  • Hand back an UnsafeMutableRawBufferPointer that covers the entire typed array.

A new byteSize property on NodeTypedArrayKind centralises the element-size mapping and mirrors the existing raw property.

Repro

let array = try NodeTypedArray<Float>(for: buffer, count: 1024)
try array.withUnsafeMutableBytes { buf in
    print(buf.count) // before: 256, after: 1024
}

Notes

  • No behaviour change for Int8 / UInt8 / Uint8Clamped arrays.
  • The pre-existing // TODO: Do we need to advance data by offset/a multiple of offset? is removed; napi_get_typedarray_info already returns data adjusted by the byte offset, per the Node-API spec.

`napi_get_typedarray_info` returns the typed array's *element* count in its `length` out-parameter, not its byte count. The previous implementation passed that element count straight into the `UnsafeMutableRawBufferPointer` it handed back, which silently truncated the buffer for any non-byte typed array.
@liautaud
Copy link
Copy Markdown
Author

(cc. @kabiroberai)

@liautaud liautaud changed the title Fix byte count in NodeAnyTypedArray.withUnsafeMutableRawBytes. Fix byte count in NodeAnyTypedArray.withUnsafeMutableRawBytes Apr 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant