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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
use crate::{
Alpha, Channel, Ch8, Ch16, Ch32, Format, Opaque, PixModes, Translucent,
};
#[derive(Clone, Copy, Debug, Default, PartialEq)]
#[repr(C)]
pub struct Gray<C: Channel, A: Alpha> {
value: C,
alpha: A,
}
impl<C: Channel, A: Alpha> PixModes for Gray<C, A> { }
impl<C: Channel, A: Alpha> Iterator for Gray<C, A> {
type Item = Self;
fn next(&mut self) -> Option<Self::Item> {
Some(*self)
}
}
impl<C, A> From<u8> for Gray<C, A>
where C: Channel, C: From<Ch8>, A: Alpha, A: From<Opaque<C>>
{
fn from(c: u8) -> Self {
Gray::new(Ch8::new(c))
}
}
impl<C: Channel, A: Alpha> Gray<C, A> {
pub fn new<H>(value: H) -> Self
where C: From<H>, A: From<Opaque<C>>
{
let value = C::from(value);
let alpha = A::from(Opaque::default());
Gray { value, alpha }
}
pub fn with_alpha<H>(value: H, alpha: H) -> Self
where C: From<H>, A: From<C>
{
let value = C::from(value);
let alpha = A::from(C::from(alpha));
Gray { value, alpha }
}
pub fn value(self) -> C {
self.value
}
pub fn alpha(self) -> A {
self.alpha
}
}
impl<C, A> Format for Gray<C, A>
where C: Channel, A: Alpha<Chan=C> + From<C>
{
type Chan = C;
fn rgba(self) -> [Self::Chan; 4] {
[self.value, self.value, self.value, self.alpha.value()]
}
fn with_rgba(rgba: [Self::Chan; 4]) -> Self {
let value = rgba[0].max(rgba[1]).max(rgba[2]);
let alpha = rgba[3];
Gray::with_alpha(value, alpha)
}
fn difference(self, rhs: Self) -> Self {
let v = if self.value > rhs.value { self.value - rhs.value }
else { rhs.value - self.value };
let a = if self.alpha.value() > rhs.alpha.value() {
self.alpha.value() - rhs.alpha.value()
} else {
rhs.alpha.value() - self.alpha.value()
};
Gray::with_alpha(v, a)
}
fn within_threshold(self, rhs: Self) -> bool {
self.value <= rhs.value &&
self.alpha.value() <= rhs.alpha.value()
}
}
pub type Gray8 = Gray<Ch8, Opaque<Ch8>>;
pub type Gray16 = Gray<Ch16, Opaque<Ch16>>;
pub type Gray32 = Gray<Ch32, Opaque<Ch32>>;
pub type GrayAlpha8 = Gray<Ch8, Translucent<Ch8>>;
pub type GrayAlpha16 = Gray<Ch16, Translucent<Ch16>>;
pub type GrayAlpha32 = Gray<Ch32, Translucent<Ch32>>;
#[cfg(test)]
mod test {
use super::super::*;
#[test]
fn check_sizes() {
assert_eq!(std::mem::size_of::<Gray8>(), 1);
assert_eq!(std::mem::size_of::<Gray16>(), 2);
assert_eq!(std::mem::size_of::<Gray32>(), 4);
assert_eq!(std::mem::size_of::<GrayAlpha8>(), 2);
assert_eq!(std::mem::size_of::<GrayAlpha16>(), 4);
assert_eq!(std::mem::size_of::<GrayAlpha32>(), 8);
}
}