use std::sync::Arc;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct IconImage {
width: u32,
height: u32,
rgba: Arc<[u8]>,
}
impl IconImage {
pub fn new(width: u32, height: u32, rgba: impl Into<Arc<[u8]>>) -> Option<Self> {
let rgba = rgba.into();
if width == 0 || height == 0 {
return None;
}
let expected = (width as usize).checked_mul(height as usize).and_then(|pixels| pixels.checked_mul(4));
if expected != Some(rgba.len()) {
return None;
}
Some(Self { width, height, rgba })
}
pub fn from_rgba(width: u32, height: u32, rgba: Vec<u8>) -> Option<Self> {
Self::new(width, height, rgba)
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
pub fn rgba(&self) -> &[u8] {
&self.rgba
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WindowIcon {
small: IconImage,
large: IconImage,
}
impl WindowIcon {
pub fn new(small: IconImage, large: IconImage) -> Self {
Self { small, large }
}
pub fn single(image: IconImage) -> Self {
Self { small: image.clone(), large: image }
}
pub fn small(&self) -> &IconImage {
&self.small
}
pub fn large(&self) -> &IconImage {
&self.large
}
}
#[cfg(test)]
mod tests {
use super::*;
fn solid(width: u32, height: u32) -> IconImage {
IconImage::from_rgba(width, height, vec![255; width as usize * height as usize * 4]).expect("valid rgba")
}
#[test]
fn validates_dimensions_and_length() {
assert!(IconImage::new(2, 2, vec![0; 16]).is_some());
assert!(IconImage::new(0, 2, Vec::new()).is_none(), "零宽无效");
assert!(IconImage::new(2, 2, vec![0; 15]).is_none(), "字节数不匹配");
assert!(IconImage::new(2, 2, vec![0; 20]).is_none(), "字节数不匹配");
}
#[test]
fn single_icon_shares_image() {
let image = solid(32, 32);
let icon = WindowIcon::single(image.clone());
assert_eq!(icon.small(), &image);
assert_eq!(icon.large(), &image);
assert_eq!(Arc::strong_count(&image.rgba), 3, "single 复用同一块 RGBA");
}
#[test]
fn explicit_small_and_large_are_kept() {
let small = solid(32, 32);
let large = solid(256, 256);
let icon = WindowIcon::new(small.clone(), large.clone());
assert_eq!(icon.small().width(), 32);
assert_eq!(icon.large().width(), 256);
}
}