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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
use super::super::drawable::*;
use super::super::transform::*;
use super::Image;
use coord::{Coord, ToUnsigned};
use core::marker::PhantomData;
use pixelcolor::PixelColor;
#[derive(Debug)]
pub struct Image1BPP<'a, C> {
width: u32,
height: u32,
imagedata: &'a [u8],
pub offset: Coord,
pixel_type: PhantomData<C>,
}
impl<'a, C> Image<'a> for Image1BPP<'a, C>
where
C: PixelColor,
{
fn new(imagedata: &'a [u8], width: u32, height: u32) -> Self {
Self {
width,
height,
imagedata,
offset: Coord::new(0, 0),
pixel_type: PhantomData,
}
}
}
impl<'a, C> IntoIterator for &'a Image1BPP<'a, C>
where
C: PixelColor,
{
type Item = Pixel<C>;
type IntoIter = Image1BPPIterator<'a, C>;
fn into_iter(self) -> Self::IntoIter {
Image1BPPIterator {
im: self,
x: 0,
y: 0,
}
}
}
#[derive(Debug)]
pub struct Image1BPPIterator<'a, C: 'a> {
x: u32,
y: u32,
im: &'a Image1BPP<'a, C>,
}
impl<'a, C> Iterator for Image1BPPIterator<'a, C>
where
C: PixelColor,
{
type Item = Pixel<C>;
fn next(&mut self) -> Option<Self::Item> {
if (self.im.offset[0] + self.im.width as i32) < 0
&& (self.im.offset[1] + self.im.height as i32) < 0
{
return None;
}
let current_pixel = loop {
let w = self.im.width;
let h = self.im.height;
let x = self.x;
let y = self.y;
if x >= w || y >= h {
return None;
}
let bytes_in_row = (w / 8) + if w % 8 > 0 { 1 } else { 0 };
let row_start = bytes_in_row * y;
let row_byte_index = x / 8;
let byte_index = row_start + row_byte_index;
let bit_offset = 7 - (x - (row_byte_index * 8));
let bit_value = (self.im.imagedata[byte_index as usize] >> bit_offset) & 1;
let current_pixel = self.im.offset + Coord::new(x as i32, y as i32);
self.x += 1;
if self.x >= w {
self.x = 0;
self.y += 1;
}
if current_pixel[0] >= 0 && current_pixel[1] >= 0 {
break Pixel(current_pixel.to_unsigned(), bit_value.into());
}
};
Some(current_pixel)
}
}
impl<'a, C> Drawable for Image1BPP<'a, C> {}
impl<'a, C> Transform for Image1BPP<'a, C> {
fn translate(&self, by: Coord) -> Self {
Self {
offset: self.offset + by,
..*self.clone()
}
}
fn translate_mut(&mut self, by: Coord) -> &mut Self {
self.offset += by;
self
}
}