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
|
use std::convert::{From, Into, TryFrom};
#[derive(Debug)]
pub struct Pixmap<T> {
pub width: u32,
pub height: u32,
pub data: Vec<T>,
}
#[derive(Copy, Clone, Debug)]
pub struct MapPoint {
pub x: u32,
pub y: u32,
}
impl From<(u32, u32)> for MapPoint {
fn from((x, y): (u32, u32)) -> MapPoint {
MapPoint { x, y }
}
}
impl TryFrom<(i32, i32)> for MapPoint {
type Error = ();
fn try_from((x, y): (i32, i32)) -> Result<Self, Self::Error> {
if x < 0 || y < 0 {
return Err(());
} else {
Ok(MapPoint {
x: x as u32,
y: y as u32,
})
}
}
}
impl TryFrom<(i64, i64)> for MapPoint {
type Error = ();
fn try_from((x, y): (i64, i64)) -> Result<Self, Self::Error> {
if x < 0 || y < 0 {
return Err(());
} else {
Ok(MapPoint {
x: x as u32,
y: y as u32,
})
}
}
}
impl<T> Pixmap<T>
where
T: Copy + Clone + Default,
{
pub fn new(width: u32, height: u32) -> Self {
let data = vec![Default::default(); (width * height) as usize];
Pixmap {
width,
height,
data,
}
}
pub fn new_with(width: u32, height: u32, start: T) -> Self {
let data = vec![start; (width * height) as usize];
Pixmap {
width,
height,
data,
}
}
pub fn is_inside<P: Into<MapPoint>>(&self, pt: P) -> bool {
let MapPoint { x, y } = pt.into();
x < self.width && y < self.height
}
pub fn idx<P: Into<MapPoint>>(&self, pt: P) -> usize {
let MapPoint { x, y } = pt.into();
(y * self.width + x) as usize
}
pub fn get<P: Into<MapPoint>>(&self, pt: P) -> T {
let idx = self.idx(pt);
self.data[idx]
}
pub fn set<P: Into<MapPoint>>(&mut self, pt: P, new_val: T) -> T {
let pt = pt.into();
let old_val = self.get(pt);
let idx = self.idx(pt);
self.data[idx] = new_val;
old_val
}
}
|