near / borsh-js

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

Serialize and deserialize support for `Map` type. #41

Closed PopcornPaws closed 2 years ago

PopcornPaws commented 2 years ago

It would be nice if Borsh-js would support Map types out of the box.

For example, I would like to use a rust BTreeMap type on the contract side that can be serialized/deserialized on the client side in a Map type. As far as I know, BTreeMaps are serialized similarly to a Vec, namely there is 4 bytes reserved at the front to encode the length (size) in LE representation, then the keys and values are serialized in a sorted sequence, so, contrary to a HashMap type, there's no danger of iterating over the key-value pairs randomly.

What do you guys think?

zaxozhu commented 2 years ago

@volovyk-s would you please take a look?

volovyks commented 2 years ago

@PopcornPaws awesome contribution! Have you tested it with borsh-rs? Can we serialize it here and deserialize it in Rust and vise-versa?

PopcornPaws commented 2 years ago

@PopcornPaws awesome contribution! Have you tested it with borsh-rs? Can we serialize it here and deserialize it in Rust and vise-versa?

@volovyk-s Yep, I tested the (de)serialization of a BTreeMap<[u8; 32], Pubkey>, a BTreeMap<String, Option<u32> and a BTreeMap<u16, String> type in Rust and it worked seamlessly in both ways.

volovyks commented 2 years ago

Thank you @PopcornPaws !

PopcornPaws commented 2 years ago

@volovyk-s thank you!