1use std::{fmt, sync::Arc};
2
3use crate::core::{PhysicalSize, UiImageSource};
4
5pub type ImageSource = UiImageSource;
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8pub enum ImageStatus {
9 Loading,
10 Ready,
11 Failed,
12}
13
14pub type AssetBytes = Arc<[u8]>;
15
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub enum AssetError {
18 NotFound(String),
19 InvalidData(String),
20 Unsupported(String),
21}
22
23impl fmt::Display for AssetError {
24 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
25 match self {
26 Self::NotFound(id) => write!(formatter, "asset `{id}` was not found"),
27 Self::InvalidData(message) | Self::Unsupported(message) => formatter.write_str(message),
28 }
29 }
30}
31
32impl std::error::Error for AssetError {}
33
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub struct ImageData {
36 pub size: PhysicalSize,
37 pub bgra_premultiplied: AssetBytes,
38}
39
40impl ImageData {
41 pub fn new(size: PhysicalSize, bytes: impl Into<AssetBytes>) -> Result<Self, AssetError> {
42 let bytes = bytes.into();
43 let expected = size.width.max(0) as usize * size.height.max(0) as usize * 4;
44 if size.width <= 0 || size.height <= 0 || bytes.len() != expected {
45 return Err(AssetError::InvalidData(format!(
46 "expected {expected} BGRA bytes for {}x{}, received {}",
47 size.width,
48 size.height,
49 bytes.len()
50 )));
51 }
52 Ok(Self {
53 size,
54 bgra_premultiplied: bytes,
55 })
56 }
57}