image icon indicating copy to clipboard operation
image copied to clipboard

`ImageEncoder` trait is not `dyn` compatible

Open Shnatsel opened this issue 4 months ago • 1 comments

ImageDecoder trait has been refactored to be dyn compatible, but the ImageEncoder trait has not.

This came up in https://github.com/image-rs/image/pull/2554#issuecomment-3222022599

Shnatsel avatar Aug 26 '25 00:08 Shnatsel

For reference, the way that ImageDecoder is dyn-compatible despite consuming Self is this pair of required methods:

trait ImageDecoder {
    fn read_image(self, buf: &mut [u8]) -> ImageResult<()>
       where Self: Sized;
    fn read_image_boxed(self: Box<Self>, buf: &mut [u8]) -> ImageResult<()>;
    ...
}


impl<T: ?Sized + ImageDecoder> ImageDecoder for Box<T> {
    fn read_image(self, buf: &mut [u8]) -> ImageResult<()>
    where
        Self: Sized,
    {
        T::read_image_boxed(self, buf)
    }
    fn read_image_boxed(self: Box<Self>, buf: &mut [u8]) -> ImageResult<()> {
        T::read_image_boxed(*self, buf)
    }
    ...
}

(Technically, simply adding the Self: Sized is enough for the trait to be dyn-compatible. But you need the read_image_boxed method to actually be able to read the image data.)

fintelia avatar Aug 26 '25 02:08 fintelia