1use std::sync::Arc;
8
9#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct IconImage {
12 width: u32,
13 height: u32,
14 rgba: Arc<[u8]>,
15}
16
17impl IconImage {
18 pub fn new(width: u32, height: u32, rgba: impl Into<Arc<[u8]>>) -> Option<Self> {
20 let rgba = rgba.into();
21 if width == 0 || height == 0 {
22 return None;
23 }
24 let expected = (width as usize).checked_mul(height as usize).and_then(|pixels| pixels.checked_mul(4));
25 if expected != Some(rgba.len()) {
26 return None;
27 }
28 Some(Self { width, height, rgba })
29 }
30
31 pub fn from_rgba(width: u32, height: u32, rgba: Vec<u8>) -> Option<Self> {
33 Self::new(width, height, rgba)
34 }
35
36 pub fn width(&self) -> u32 {
37 self.width
38 }
39
40 pub fn height(&self) -> u32 {
41 self.height
42 }
43
44 pub fn rgba(&self) -> &[u8] {
45 &self.rgba
46 }
47}
48
49#[derive(Clone, Debug, PartialEq, Eq)]
51pub struct WindowIcon {
52 small: IconImage,
53 large: IconImage,
54}
55
56impl WindowIcon {
57 pub fn new(small: IconImage, large: IconImage) -> Self {
58 Self { small, large }
59 }
60
61 pub fn single(image: IconImage) -> Self {
63 Self { small: image.clone(), large: image }
64 }
65
66 pub fn small(&self) -> &IconImage {
67 &self.small
68 }
69
70 pub fn large(&self) -> &IconImage {
71 &self.large
72 }
73}
74
75#[cfg(test)]
76mod tests {
77 use super::*;
78
79 fn solid(width: u32, height: u32) -> IconImage {
80 IconImage::from_rgba(width, height, vec![255; width as usize * height as usize * 4]).expect("valid rgba")
81 }
82
83 #[test]
84 fn validates_dimensions_and_length() {
85 assert!(IconImage::new(2, 2, vec![0; 16]).is_some());
86 assert!(IconImage::new(0, 2, Vec::new()).is_none(), "零宽无效");
87 assert!(IconImage::new(2, 2, vec![0; 15]).is_none(), "字节数不匹配");
88 assert!(IconImage::new(2, 2, vec![0; 20]).is_none(), "字节数不匹配");
89 }
90
91 #[test]
92 fn single_icon_shares_image() {
93 let image = solid(32, 32);
94 let icon = WindowIcon::single(image.clone());
95 assert_eq!(icon.small(), &image);
96 assert_eq!(icon.large(), &image);
97 assert_eq!(Arc::strong_count(&image.rgba), 3, "single 复用同一块 RGBA");
98 }
99
100 #[test]
101 fn explicit_small_and_large_are_kept() {
102 let small = solid(32, 32);
103 let large = solid(256, 256);
104 let icon = WindowIcon::new(small.clone(), large.clone());
105 assert_eq!(icon.small().width(), 32);
106 assert_eq!(icon.large().width(), 256);
107 }
108}