1use std::fmt;
4
5#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct RgbImage {
8 width: usize,
9 height: usize,
10 data: Vec<u8>,
11}
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct ImageSizeError {
16 pub width: usize,
17 pub height: usize,
18 pub channels: usize,
19 pub len: usize,
20}
21
22impl fmt::Display for ImageSizeError {
23 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24 write!(
25 f,
26 "{}×{} image with {} channel(s) needs {} bytes, got {}",
27 self.width,
28 self.height,
29 self.channels,
30 self.width * self.height * self.channels,
31 self.len
32 )
33 }
34}
35
36impl std::error::Error for ImageSizeError {}
37
38impl RgbImage {
39 pub fn new(width: usize, height: usize, data: Vec<u8>) -> Result<Self, ImageSizeError> {
41 if data.len() != width * height * 3 {
42 return Err(ImageSizeError {
43 width,
44 height,
45 channels: 3,
46 len: data.len(),
47 });
48 }
49 Ok(Self {
50 width,
51 height,
52 data,
53 })
54 }
55
56 pub fn from_gray(width: usize, height: usize, gray: &[u8]) -> Result<Self, ImageSizeError> {
59 if gray.len() != width * height {
60 return Err(ImageSizeError {
61 width,
62 height,
63 channels: 1,
64 len: gray.len(),
65 });
66 }
67 let data = gray.iter().flat_map(|&v| [v, v, v]).collect();
68 Ok(Self {
69 width,
70 height,
71 data,
72 })
73 }
74
75 pub fn width(&self) -> usize {
76 self.width
77 }
78
79 pub fn height(&self) -> usize {
80 self.height
81 }
82
83 pub fn data(&self) -> &[u8] {
85 &self.data
86 }
87
88 pub fn pixel(&self, x: usize, y: usize) -> [u8; 3] {
90 let i = 3 * (y * self.width + x);
91 [self.data[i], self.data[i + 1], self.data[i + 2]]
92 }
93}
94
95#[cfg(test)]
96mod tests {
97 use super::*;
98
99 #[test]
100 fn checks_the_buffer_size_and_replicates_gray() {
101 assert!(RgbImage::new(2, 2, vec![0; 11]).is_err());
102 let image = RgbImage::from_gray(2, 1, &[10, 200]).unwrap();
103 assert_eq!(image.pixel(1, 0), [200, 200, 200]);
104 assert_eq!(image.data().len(), 6);
105 let error = RgbImage::from_gray(3, 3, &[0; 8]).unwrap_err();
106 assert_eq!(
107 error.to_string(),
108 "3×3 image with 1 channel(s) needs 9 bytes, got 8"
109 );
110 }
111}