aboutsummaryrefslogtreecommitdiff
path: root/src/bitmap.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/bitmap.rs')
-rw-r--r--src/bitmap.rs89
1 files changed, 89 insertions, 0 deletions
diff --git a/src/bitmap.rs b/src/bitmap.rs
new file mode 100644
index 0000000..01a39d9
--- /dev/null
+++ b/src/bitmap.rs
@@ -0,0 +1,89 @@
1use std::convert::{From, Into, TryFrom};
2
3#[derive(Debug)]
4pub struct Pixmap<T> {
5 pub width: u32,
6 pub height: u32,
7 pub data: Vec<T>,
8}
9
10#[derive(Copy, Clone, Debug)]
11pub struct MapPoint {
12 pub x: u32,
13 pub y: u32,
14}
15
16impl From<(u32, u32)> for MapPoint {
17 fn from((x, y): (u32, u32)) -> MapPoint {
18 MapPoint { x, y }
19 }
20}
21
22impl TryFrom<(i32, i32)> for MapPoint {
23 type Error = ();
24 fn try_from((x, y): (i32, i32)) -> Result<Self, Self::Error> {
25 if x < 0 || y < 0 {
26 return Err(());
27 } else {
28 Ok(MapPoint {
29 x: x as u32,
30 y: y as u32,
31 })
32 }
33 }
34}
35
36impl TryFrom<(i64, i64)> for MapPoint {
37 type Error = ();
38 fn try_from((x, y): (i64, i64)) -> Result<Self, Self::Error> {
39 if x < 0 || y < 0 {
40 return Err(());
41 } else {
42 Ok(MapPoint {
43 x: x as u32,
44 y: y as u32,
45 })
46 }
47 }
48}
49
50impl<T> Pixmap<T>
51where
52 T: Copy + Clone + Default,
53{
54 pub fn new(width: u32, height: u32) -> Self {
55 let data = vec![Default::default(); (width * height) as usize];
56 Pixmap {
57 width,
58 height,
59 data,
60 }
61 }
62 pub fn new_with(width: u32, height: u32, start: T) -> Self {
63 let data = vec![start; (width * height) as usize];
64 Pixmap {
65 width,
66 height,
67 data,
68 }
69 }
70 pub fn is_inside<P: Into<MapPoint>>(&self, pt: P) -> bool {
71 let MapPoint { x, y } = pt.into();
72 x < self.width && y < self.height
73 }
74 pub fn idx<P: Into<MapPoint>>(&self, pt: P) -> usize {
75 let MapPoint { x, y } = pt.into();
76 (y * self.width + x) as usize
77 }
78 pub fn get<P: Into<MapPoint>>(&self, pt: P) -> T {
79 let idx = self.idx(pt);
80 self.data[idx]
81 }
82 pub fn set<P: Into<MapPoint>>(&mut self, pt: P, new_val: T) -> T {
83 let pt = pt.into();
84 let old_val = self.get(pt);
85 let idx = self.idx(pt);
86 self.data[idx] = new_val;
87 old_val
88 }
89}