Help with conflicting implementation

Hello. I’m also having problems with conflicting implementations, and I can see why.

I would like to have a default implementation when <T: IntoBytes>, but I’d like to have a better version when I know the size. Is there a way to tell rust that I want the first when T is IntoBytes but is not SizedBytes?

I tried <T: IntoBytes + !SizedBytes>, and <T: IntoBytes + ?SizedBytes>, but the first is not a valid syntax and the second is not quite what I want.

Is there any way to achieve this?

pub trait SizedBytes {
    const BYTES_LENGTH: usize;
}

pub trait IntoBytes {
    fn into_bytes(&self) -> Vec<u8>;
}

impl<T: IntoBytes> IntoBytes for Vec<T> {
    fn into_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(16);
        for into in self {
            bytes.extend(bytes.into_bytes());
        }
        bytes
    }
}

impl<T: IntoBytes + SizedBytes> IntoBytes for Vec<T> {
    fn into_bytes(&self) -> Vec<u8> {
        let mut bytes = Vec::with_capacity(self.len() * T::BYTES_LENGTH);
        for into in self {
            bytes.extend(bytes.into_bytes());
        }
        bytes
    }
}

This looks like a case that wants specialization:

Aw, so it can’t be done right now?
I’m subscribing to that issue.

Thank you.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.