borsh-rs icon indicating copy to clipboard operation
borsh-rs copied to clipboard

Discussion: support on 3rd party containers

Open ailisp opened this issue 4 years ago • 2 comments

When implement borshSerialize on some wasmer cache object, there's some fields using cranelift_entity::{PrimaryMap, SecondaryMap} and indexmap::IndexMap, but they do not have BorshSerialize implemented, which make entire structs not derivable. We also cannot implement it in borsh-rs repo, which would make borsh depends on these 3rd party crates (although we might consider optional dependency, it's still not good, because of 1. version of this libs, 2. hard to exhaust all 3rd party libs) #8 is also an option, but not good for performance. The best way I can think of is let these container library user implement helper functions, for example:

fn borsh_serialize_index_map<K: BorshSerialize, V:BroshSerialize, W: std::io::Write>(index_map: &IndexMap<K, V>, writer: &mut W) -> std::io::Result<()> {

fn borsh_deserialize_index_map<K: BorshSerialize, V:BroshSerialize>(buf: &mut &[u8]) -> std::io::Result<IndexMap<K, V>> {

and derive struct that contains these containers with a macro marker:

#[derive(BorshSerialize, BorshDeserialize)]
struct SomeStruct {
...
    #[borsh_ser(borsh_serialize_index_map)]
    #[borsh_deser(borsh_deserialize_index_map)]
    s: IndexMap<String, u32>,
...
}

Any better ways?

ailisp avatar Feb 16 '21 23:02 ailisp

It should be possible to implement a wrapper struct, which would have the Borsh implementation on it. What do you think?

frol avatar Feb 16 '21 23:02 frol

Wrapper struct is also an option, but would cause changes to existing code for example above snippet all occurence of SomeStruct.s become SomeStruct.s.0 or SomeStruct.s.name. I use this approach here (exports: IndexMap => struct ExportsMap(map: IndexMap): https://github.com/near/wasmer/pull/1/files, it's a more than 10 file change, whereas #[borsh_ser(borsh_serialize_index_map)] would be change only one place, so i think it's more appealing

ailisp avatar Feb 17 '21 00:02 ailisp