near / borsh-js

TypeScript/JavaScript implementation of Binary Object Representation Serializer for Hashing
Apache License 2.0
112 stars 38 forks source link

How to (de)serialize unnamed fields #80

Closed kayac-chang closed 8 months ago

kayac-chang commented 10 months ago

In https://borsh.io/, the specification mentions there are unnamed fields, but don't mention it in the documentation.

Suppose we have type (u64, u64, u64, u8, Option<u8>, u64), how did we (de)serialize with this type?

hanakannzashi commented 9 months ago

This is same as a struct in js

interface ExampleTuple {
  0: bigint;
  1: bigint;
  2: bigint;
  3: number;
  4: number | null;
  5: bigint;
}
gagdiez commented 8 months ago

@kayac-chang indeed, not every Rust has a 1:1 mapping with Javascript types.

unnamed fields will be serialized in memory as: [u64, u64, u64, u8, option-bit, u8, u64], so a Class/Interface that follows that pattern will be able to deserialize it. The solution proposed by @hanakannzashi is a valid one.

Note: The names in the fields only help to know where to put the deserialised value in the object being created.