use mln_style::bitmap::PremultipliedImage;
use mln_style::error::Error;
use crate::image::image::{ImageType, UNSUPPORTED, image_type};
pub(crate) type DecodeResult = Result<PremultipliedImage, Error>;
#[cfg(target_family = "wasm")]
pub(crate) type DecodeDone = Box<dyn FnOnce(DecodeResult)>;
#[cfg(target_family = "wasm")]
pub(crate) trait ImageDecoder: Send + Sync {
fn decode(&self, data: &[u8], kind: ImageType, done: DecodeDone);
}
pub(crate) fn decode(data: &[u8], done: impl FnOnce(DecodeResult) + 'static) {
let Some(kind) = image_type(data) else {
done(Err(Error::unsupported(UNSUPPORTED)));
return;
};
platform_decode(data, kind, done);
}
#[cfg(not(target_family = "wasm"))]
fn platform_decode(data: &[u8], _kind: ImageType, done: impl FnOnce(DecodeResult)) {
done(crate::image::image::decode_image(data));
}
#[cfg(target_family = "wasm")]
fn platform_decode(data: &[u8], kind: ImageType, done: impl FnOnce(DecodeResult) + 'static) {
crate::image::browser_decoder::BrowserDecoder.decode(data, kind, Box::new(done));
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use std::rc::Rc;
use super::*;
fn decode_now(data: &[u8]) -> DecodeResult {
let result = Rc::new(RefCell::new(None));
let slot = Rc::clone(&result);
decode(data, move |r| *slot.borrow_mut() = Some(r));
result.take().expect("the default decoder answers before returning")
}
#[test]
fn native_decoder_answers_at_once() {
assert_eq!(decode_now(b"GIF89a").unwrap_err().message, UNSUPPORTED);
let png = crate::image::encode_png(&PremultipliedImage::from_vec(
mln_style::size::Size::new(1, 1),
vec![64, 0, 0, 128],
));
let image = decode_now(&png).unwrap();
assert_eq!(image.data, vec![64, 0, 0, 128]);
}
}