jhugman / uniffi-bindgen-react-native

A uniffi bindings generator for calling Rust from react-native
Other
0 stars 0 forks source link

Use DataView instead of TypedArrays in RustBuffer #57

Closed jhugman closed 1 month ago

jhugman commented 1 month ago

Using typed arrays had a number of disadvantages, most notably:

This resulted in lots of copying. For example, when writing a BigInt to the byte offset 11 a destination ArrayBuffer:

  1. an transitional ArrayBuffer of 8 bytes was created
  2. a Uint64Array typed array was created to view that transitional ArrayBuffer.
  3. the BigInt was written into the Uint64Array, i.e. the transitional array.
  4. the transitional array was reversed, because of endian-ness differences between Rust and Hermes.
  5. a Uint8Array view was created for each of the transitional array and the destination array.
  6. the transitional array was copied into the destination array.

This was a lot of work for a single write: steps 1, 3, 4 and 6 involve O(n) work.

This PR replaces the typed arrays with a DataView which is a lot simpler:

  1. a DataView of the destination array is created
  2. the BigInt is written into the DataView, of the correct endianness.

Only step 2 involves O(n) work.

The work allowed us to simplify the RustBuffer: the read and write method are both replaced by two simpler methods: