1use std::{collections::TryReserveError, error::Error, fmt};
4
5use crate::identity::ApplicationId;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct ImageAssetLimits {
14 max_images: usize,
15 max_width: u32,
16 max_height: u32,
17 max_pixel_bytes: usize,
18}
19
20impl ImageAssetLimits {
21 pub const fn new(
25 max_images: usize,
26 max_width: u32,
27 max_height: u32,
28 max_pixel_bytes: usize,
29 ) -> Self {
30 Self {
31 max_images,
32 max_width,
33 max_height,
34 max_pixel_bytes,
35 }
36 }
37
38 pub const fn max_images(self) -> usize {
40 self.max_images
41 }
42
43 pub const fn max_width(self) -> u32 {
45 self.max_width
46 }
47
48 pub const fn max_height(self) -> u32 {
50 self.max_height
51 }
52
53 pub const fn max_pixel_bytes(self) -> usize {
55 self.max_pixel_bytes
56 }
57}
58
59impl Default for ImageAssetLimits {
60 fn default() -> Self {
62 Self::new(64, 4096, 4096, 64 * 1024 * 1024)
63 }
64}
65
66#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub struct ImageAssetId {
74 application: ApplicationId,
75 slot: usize,
76 width: u32,
77 height: u32,
78}
79
80impl ImageAssetId {
81 pub const fn width(self) -> u32 {
83 self.width
84 }
85
86 pub const fn height(self) -> u32 {
88 self.height
89 }
90}
91
92#[derive(Debug)]
99pub struct ImageAsset {
100 width: u32,
101 height: u32,
102 pixels: Vec<u8>,
103}
104
105impl ImageAsset {
106 pub const fn width(&self) -> u32 {
108 self.width
109 }
110
111 pub const fn height(&self) -> u32 {
113 self.height
114 }
115
116 pub fn pixels(&self) -> &[u8] {
118 &self.pixels
119 }
120}
121
122#[derive(Debug)]
124#[non_exhaustive]
125pub enum ImageAssetError {
126 InvalidDimensions {
128 width: u32,
130 height: u32,
132 },
133 DimensionsExceeded {
135 width: u32,
137 height: u32,
139 max_width: u32,
141 max_height: u32,
143 },
144 PixelByteCountOverflow {
146 width: u32,
148 height: u32,
150 },
151 PixelLengthMismatch {
153 expected: usize,
155 actual: usize,
157 },
158 ImageLimitExceeded {
160 limit: usize,
162 },
163 PixelByteLimitExceeded {
165 limit: usize,
167 retained: usize,
169 incoming: usize,
171 },
172 AllocationFailed {
174 source: TryReserveError,
176 },
177}
178
179impl fmt::Display for ImageAssetError {
180 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
181 match self {
182 Self::InvalidDimensions { width, height } => write!(
183 formatter,
184 "image dimensions must be positive, got {width} by {height}"
185 ),
186 Self::DimensionsExceeded {
187 width,
188 height,
189 max_width,
190 max_height,
191 } => write!(
192 formatter,
193 "image dimensions {width} by {height} exceed limits {max_width} by {max_height}"
194 ),
195 Self::PixelByteCountOverflow { width, height } => write!(
196 formatter,
197 "RGBA8 byte length overflows for image dimensions {width} by {height}"
198 ),
199 Self::PixelLengthMismatch { expected, actual } => write!(
200 formatter,
201 "RGBA8 image requires exactly {expected} bytes, got {actual}"
202 ),
203 Self::ImageLimitExceeded { limit } => {
204 write!(
205 formatter,
206 "image registry reached its limit of {limit} entries"
207 )
208 }
209 Self::PixelByteLimitExceeded {
210 limit,
211 retained,
212 incoming,
213 } => write!(
214 formatter,
215 "image pixel capacity {retained} plus {incoming} bytes exceeds limit {limit}"
216 ),
217 Self::AllocationFailed { source } => {
218 write!(formatter, "image asset storage allocation failed: {source}")
219 }
220 }
221 }
222}
223
224impl Error for ImageAssetError {
225 fn source(&self) -> Option<&(dyn Error + 'static)> {
226 match self {
227 Self::AllocationFailed { source } => Some(source),
228 _ => None,
229 }
230 }
231}
232
233#[derive(Debug)]
234pub(crate) struct ImageAssetRegistry {
235 application: ApplicationId,
236 limits: ImageAssetLimits,
237 images: Vec<ImageAsset>,
238 pixel_bytes: usize,
239}
240
241impl ImageAssetRegistry {
242 pub(crate) const fn new(application: ApplicationId, limits: ImageAssetLimits) -> Self {
243 Self {
244 application,
245 limits,
246 images: Vec::new(),
247 pixel_bytes: 0,
248 }
249 }
250
251 pub(crate) fn register(
252 &mut self,
253 width: u32,
254 height: u32,
255 pixels: &[u8],
256 ) -> Result<ImageAssetId, ImageAssetError> {
257 if width == 0 || height == 0 {
258 return Err(ImageAssetError::InvalidDimensions { width, height });
259 }
260 if width > self.limits.max_width || height > self.limits.max_height {
261 return Err(ImageAssetError::DimensionsExceeded {
262 width,
263 height,
264 max_width: self.limits.max_width,
265 max_height: self.limits.max_height,
266 });
267 }
268 let pixel_length = usize::try_from(width)
269 .ok()
270 .zip(usize::try_from(height).ok())
271 .and_then(|(width, height)| width.checked_mul(height))
272 .and_then(|texels| texels.checked_mul(4))
273 .ok_or(ImageAssetError::PixelByteCountOverflow { width, height })?;
274 if pixels.len() != pixel_length {
275 return Err(ImageAssetError::PixelLengthMismatch {
276 expected: pixel_length,
277 actual: pixels.len(),
278 });
279 }
280 if self.images.len() >= self.limits.max_images {
281 return Err(ImageAssetError::ImageLimitExceeded {
282 limit: self.limits.max_images,
283 });
284 }
285 self.check_pixel_capacity(pixel_length)?;
286 let mut owned = Vec::new();
287 owned
288 .try_reserve_exact(pixel_length)
289 .map_err(|source| ImageAssetError::AllocationFailed { source })?;
290 self.check_pixel_capacity(owned.capacity())?;
293 owned.extend_from_slice(pixels);
294 self.images
295 .try_reserve_exact(1)
296 .map_err(|source| ImageAssetError::AllocationFailed { source })?;
297 let id = ImageAssetId {
298 application: self.application,
299 slot: self.images.len(),
300 width,
301 height,
302 };
303 self.pixel_bytes += owned.capacity();
304 self.images.push(ImageAsset {
305 width,
306 height,
307 pixels: owned,
308 });
309 Ok(id)
310 }
311
312 pub(crate) fn get(&self, id: ImageAssetId) -> Option<&ImageAsset> {
313 if id.application != self.application {
314 return None;
315 }
316 self.images
317 .get(id.slot)
318 .filter(|image| image.width == id.width && image.height == id.height)
319 }
320
321 pub(crate) fn len(&self) -> usize {
322 self.images.len()
323 }
324
325 pub(crate) const fn pixel_bytes(&self) -> usize {
326 self.pixel_bytes
327 }
328
329 fn check_pixel_capacity(&self, incoming: usize) -> Result<(), ImageAssetError> {
330 if incoming > self.limits.max_pixel_bytes.saturating_sub(self.pixel_bytes) {
331 return Err(ImageAssetError::PixelByteLimitExceeded {
332 limit: self.limits.max_pixel_bytes,
333 retained: self.pixel_bytes,
334 incoming,
335 });
336 }
337 Ok(())
338 }
339}
340
341#[cfg(test)]
342#[path = "image_tests.rs"]
343mod tests;