babla34
babla34

Reputation: 25

Wrapper over Borsh Serialization/Deserialization methods in Rust

I have a struct A which implements BorshDeserialize and BorshSerialize as follows

#[derive(Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
struct A {
   a : i32,
   b:  String,
}

I know I can serialize or deserialize A when I do the following:-

let s = A {a: 1 , b: "a".to_string()};

// Serialize 
let serialzed_data = s.try_to_vec().unwrap()

// Deserialize
deserialized_struct = A::try_from_slice(&serialzed_data).unwrap();

I am trying to wrap over these two methods by creating two general traits on main.rs where I import this struct from another file a.rs.

pub trait Serializable<T: BorshSerialize> {
    fn serialize(s: T) -> Vec<u8> {
        s.try_to_vec().unwrap()
    }
}

pub trait Deserializable<T : BorshDeserialize> {
    fn deserialize(s: &[u8]) -> Result<T, ()> {
        let deserialized_val = match T::try_from_slice(&s) {
            Ok(val) => {val},
            Err(_) => {return Err(());},
        };
        Ok(deserialized_val)
    }
}

where I implement Serialize and Deserialize for A as follows on a.rs

impl Serializable<A> for A {}
impl Deserializable<A> for A {}

But in the source code when I call the method serialize on A for this instruction,

A::serialize(&some_instance_of_A).unwrap()

I get the following error

A::serialize(&some_instance_of_A).unwrap()
   ^^^^^^^^^ multiple `serialize` found
   |
   = note: candidate #1 is defined in an impl of the trait `Serializable` for the type `A`
   = note: candidate #2 is defined in an impl of the trait `BorshSerialize` for the type `A`

help: disambiguate the associated function for candidate #1
   |
46 |   <&Self as A::Serializable>::serialize(&some_instance_of_A), // TODO. See issue #64
   |                                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
help: disambiguate the associated function for candidate #2
   |
46 |   <&A as BorshSerialize>::serialize(&some_instance_of_A).concat(), // TODO. See issue #64
   |

I understand that the compiler gets confused by the two instances of serialization schemes created(one due to Borsh from derive macro and the other from Serialize trait on main.rs). Is there a way to directly make the serialize call fall to BorshSerialize by default when A::serialize is called.

Upvotes: 2

Views: 828

Answers (1)

trust_nickol
trust_nickol

Reputation: 2114

By preventing to import the BorshSerialize trait you can get rid of the error.

With only the Serializable trait in scope, only one method can be called:

#[derive(Clone, PartialEq, Eq, borsh::BorshSerialize, borsh::BorshDeserialize)]
struct A {
    a : i32,
    b:  String,
}

impl Serializable for A {}

fn main() {
    let a = A { a: 0, b: String::from("") };
    let vec = a.serialize();
    eprintln!("{:?}", vec);
}

pub trait Serializable: borsh::BorshSerialize {
    fn serialize(&self) -> Vec<u8> {
        self.try_to_vec().unwrap()
    }
}

pub trait Deserializable<T : borsh::BorshDeserialize> {
    fn deserialize(s: &[u8]) -> Result<T, ()> {
        let deserialized_val = match T::try_from_slice(&s) {
            Ok(val) => {val},
            Err(_) => {return Err(());},
        };
        Ok(deserialized_val)
    }
}

Upvotes: 1

Related Questions