Skip to content
This repository was archived by the owner on Aug 15, 2025. It is now read-only.
This repository was archived by the owner on Aug 15, 2025. It is now read-only.

Implementing Encode / Decode for an arbitrary type #744

@ccleve

Description

@ccleve

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?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions