bincode icon indicating copy to clipboard operation
bincode copied to clipboard

Implementing Encode / Decode for an arbitrary type

Open ccleve opened this issue 1 year ago • 2 comments

I need to serialize SmallVec, which doesn't know about bincode or implement Encode / Decode.

When I try this:

impl Encode for SmallVec<[u8; 8]> {
    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
        todo!()
    }
}

I get this: error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate

The only workaround I can find is to implement a wrapper type:

pub struct LocalSmallVec(SmallVec<[u8; 8]>);

// Implement Encode for the LocalSmallVec wrapper type
impl Encode for LocalSmallVec {
    fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
        self.0.as_slice().encode(encoder) // Delegate to Slice's Encode implementation
    }
}

But that messes up the rest of my code. I don't want to have to refer to the contents of my arbitrary type with a ".0" prefix everywhere.

Is there a general solution to this problem?

ccleve avatar Feb 24 '25 18:02 ccleve

Serde provides remote types as a general solution which could possibly be adopted for Encode/Decode. It also provides field attributes to direct (de)serialize towards ad-hoc functions/modules, e.g. with which could similarly be adopted here.

adamreichold avatar Feb 24 '25 19:02 adamreichold

For now you can do #[bincode(with_serde)]. There is some previous discussion in #612 . We could probably implement with at some point but we'll probably introduce that in a patch release

VictorKoenders avatar Feb 26 '25 06:02 VictorKoenders