1use std::fmt::{Debug, Formatter, Result as FmtResult};
2use std::sync::Arc;
3use std::sync::atomic::{AtomicU64, Ordering};
4use thiserror::Error;
5
6static NEXT_IMAGE: AtomicU64 = AtomicU64::new(1);
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
9pub enum ImageFormat {
10 Rgba8,
11 Alpha8,
12}
13
14impl ImageFormat {
15 pub fn bytes_per_pixel(self) -> u32 {
16 match self {
17 ImageFormat::Rgba8 => 4,
18 ImageFormat::Alpha8 => 1,
19 }
20 }
21}
22
23#[derive(Clone, Debug, Error, PartialEq, Eq)]
24pub enum ImageError {
25 #[error(
26 "image is {width}x{height} but {actual} bytes were given where {expected} were expected"
27 )]
28 SizeMismatch {
29 width: u32,
30 height: u32,
31 expected: usize,
32 actual: usize,
33 },
34 #[error("image has no pixels")]
35 Empty,
36}
37
38#[derive(Clone)]
39pub struct ImageData {
40 id: u64,
41 width: u32,
42 height: u32,
43 format: ImageFormat,
44 pixels: Arc<[u8]>,
45}
46
47impl ImageData {
48 fn new(
49 width: u32,
50 height: u32,
51 format: ImageFormat,
52 pixels: Vec<u8>,
53 ) -> Result<Self, ImageError> {
54 let expected = width as usize * height as usize * format.bytes_per_pixel() as usize;
55 if expected == 0 {
56 return Err(ImageError::Empty);
57 }
58 if pixels.len() != expected {
59 return Err(ImageError::SizeMismatch {
60 width,
61 height,
62 expected,
63 actual: pixels.len(),
64 });
65 }
66 let id = NEXT_IMAGE.fetch_add(1, Ordering::Relaxed);
67 Ok(ImageData {
68 id,
69 width,
70 height,
71 format,
72 pixels: pixels.into(),
73 })
74 }
75
76 pub fn rgba8(width: u32, height: u32, mut pixels: Vec<u8>) -> Result<Self, ImageError> {
77 for pixel in pixels
78 .as_chunks_mut::<4>()
79 .0
80 .iter_mut()
81 .filter(|pixel| pixel[3] != 255)
82 {
83 let alpha = u32::from(pixel[3]);
84 for channel in &mut pixel[..3] {
85 *channel = ((u32::from(*channel) * alpha + 127) / 255) as u8;
86 }
87 }
88 Self::new(width, height, ImageFormat::Rgba8, pixels)
89 }
90
91 pub fn premultiplied_rgba8(
92 width: u32,
93 height: u32,
94 pixels: Vec<u8>,
95 ) -> Result<Self, ImageError> {
96 Self::new(width, height, ImageFormat::Rgba8, pixels)
97 }
98
99 pub fn alpha8(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self, ImageError> {
100 Self::new(width, height, ImageFormat::Alpha8, pixels)
101 }
102
103 pub fn id(&self) -> u64 {
104 self.id
105 }
106
107 pub fn width(&self) -> u32 {
108 self.width
109 }
110
111 pub fn height(&self) -> u32 {
112 self.height
113 }
114
115 pub fn format(&self) -> ImageFormat {
116 self.format
117 }
118
119 pub fn pixels(&self) -> &[u8] {
120 &self.pixels
121 }
122
123 pub fn byte_len(&self) -> u64 {
124 self.pixels.len() as u64
125 }
126}
127
128impl PartialEq for ImageData {
129 fn eq(&self, other: &Self) -> bool {
130 self.id == other.id
131 }
132}
133
134impl Eq for ImageData {}
135
136impl Debug for ImageData {
137 fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
138 write!(
139 f,
140 "ImageData({}, {}x{}, {:?})",
141 self.id, self.width, self.height, self.format
142 )
143 }
144}