1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#![deny(clippy::all)]
pub use image;
use crate::errors::SicCoreError;
use image::{DynamicImage, Frames};
use std::convert::TryFrom;
use std::fmt::{Debug, Formatter};
pub mod errors;
#[derive(Clone, Debug)]
pub enum SicImage {
Animated(AnimatedImage),
Static(image::DynamicImage),
}
#[doc(hidden)]
impl AsRef<image::DynamicImage> for SicImage {
fn as_ref(&self) -> &DynamicImage {
match self {
Self::Animated(_) => unimplemented!(),
Self::Static(image) => image,
}
}
}
impl From<image::DynamicImage> for SicImage {
fn from(item: DynamicImage) -> Self {
Self::Static(item)
}
}
impl TryFrom<SicImage> for image::DynamicImage {
type Error = SicCoreError;
fn try_from(value: SicImage) -> Result<Self, Self::Error> {
match value {
SicImage::Static(image) => Ok(image),
_ => Err(SicCoreError::RequiresStaticImage),
}
}
}
#[derive(Clone)]
pub struct AnimatedImage {
frames: Vec<image::Frame>,
}
impl AnimatedImage {
pub fn from_frames(frames: Vec<image::Frame>) -> Self {
Self { frames }
}
pub fn try_into_static_image(
mut self,
index: usize,
) -> Result<image::DynamicImage, SicCoreError> {
let len = self.frames.len();
if index < len {
Ok(image::DynamicImage::ImageRgba8(
self.frames.remove(index).into_buffer(),
))
} else {
Err(SicCoreError::InvalidFrameIndex { index, len })
}
}
pub fn frames(&self) -> &[image::Frame] {
&self.frames
}
pub fn frames_mut(&mut self) -> &mut [image::Frame] {
&mut self.frames
}
pub fn collect_frames(&self) -> Vec<image::Frame> {
self.frames.clone()
}
}
impl<'frames> TryFrom<image::Frames<'frames>> for AnimatedImage {
type Error = SicCoreError;
fn try_from(item: Frames<'frames>) -> Result<Self, Self::Error> {
let frames = item.collect_frames().map_err(SicCoreError::ImageError)?;
Ok(Self { frames })
}
}
impl Debug for AnimatedImage {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.write_fmt(format_args!(
"AnimatedImage(frame_count={})",
self.frames.len()
))
}
}