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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
use smallstr::SmallString;
use std::{convert::TryFrom, marker::PhantomData, ops::Not};

/// Number of characters below which the [`Chunks`] iterator does not allocate.
pub const CHUNK_WIDTH: usize = 4;

/// A type implementing `DisplayWidth` has a constant width for display and parsing.
///
/// This makes it suitable for 2d cartesian maps.
pub trait DisplayWidth {
    const DISPLAY_WIDTH: usize;

    /// Split a string into an iterator of chunks of characters of length `DISPLAY_WIDTH`
    fn chunks(s: &str) -> Chunks<Self> {
        Chunks(s.chars(), PhantomData)
    }
}

/// Iterator of chunks of equal width from a string.
///
/// Created with [`DisplayWidth::chunks`]. Never heap-allocates if `T::DISPLAY_WIDTH <= CHUNK_WIDTH`.
pub struct Chunks<'a, T: ?Sized>(std::str::Chars<'a>, PhantomData<T>);

impl<'a, T: DisplayWidth> Iterator for Chunks<'a, T> {
    // 4 bytes in a max-width char
    type Item = SmallString<[u8; 4 * CHUNK_WIDTH]>;

    fn next(&mut self) -> Option<Self::Item> {
        let mut s = SmallString::new();
        for _ in 0..T::DISPLAY_WIDTH {
            s.push(self.0.next()?);
        }
        Some(s)
    }
}

/// A type implementing `ToRgb` can be converted to a single color.
///
/// This is useful for rendering map tiles.
pub trait ToRgb {
    fn to_rgb(&self) -> [u8; 3];
}

/// A Tile which is compatible with booleans
#[derive(
    Clone,
    Copy,
    Debug,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    parse_display::Display,
    parse_display::FromStr,
)]
pub enum Bool {
    #[display("#")]
    True,
    #[display(".")]
    False,
}

impl Default for Bool {
    fn default() -> Self {
        Bool::False
    }
}

impl DisplayWidth for Bool {
    const DISPLAY_WIDTH: usize = 1;
}

impl PartialEq<bool> for Bool {
    fn eq(&self, other: &bool) -> bool {
        (*self == Bool::True) == *other
    }
}

impl Not for Bool {
    type Output = Bool;

    fn not(self) -> Bool {
        match self {
            Bool::True => Bool::False,
            Bool::False => Bool::True,
        }
    }
}

impl From<Bool> for bool {
    fn from(b: Bool) -> bool {
        match b {
            Bool::True => true,
            Bool::False => false,
        }
    }
}

impl From<bool> for Bool {
    fn from(b: bool) -> Bool {
        if b {
            Bool::True
        } else {
            Bool::False
        }
    }
}

impl ToRgb for Bool {
    fn to_rgb(&self) -> [u8; 3] {
        if (*self).into() {
            // warm white
            [253, 244, 220]
        } else {
            [0, 0, 0]
        }
    }
}

/// A Tile which contains a single digit.
///
/// Its range is `0..=9`.
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    parse_display::Display,
    parse_display::FromStr,
)]
#[from_str(regex = r"(?P<0>\d)")]
pub struct Digit(u8);

impl DisplayWidth for Digit {
    const DISPLAY_WIDTH: usize = 1;
}

impl From<Digit> for u8 {
    fn from(Digit(value): Digit) -> Self {
        value
    }
}

impl TryFrom<u8> for Digit {
    type Error = ();

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        (value < 10).then(move || Digit(value)).ok_or(())
    }
}

impl ToRgb for Digit {
    fn to_rgb(&self) -> [u8; 3] {
        const STEP: u8 = u8::MAX / 9;
        let value = self.0 * STEP;
        [value, value, value]
    }
}

/// A Tile which contains two digits.
///
/// Its range is `0..=99`.
#[derive(
    Clone,
    Copy,
    Debug,
    Default,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    parse_display::Display,
    parse_display::FromStr,
)]
#[display(" {0:02}")]
#[from_str(regex = r"  ?(?P<0>\d?\d)")]
pub struct TwoDigits(u8);

impl DisplayWidth for TwoDigits {
    const DISPLAY_WIDTH: usize = 3;
}

impl From<TwoDigits> for u8 {
    fn from(TwoDigits(value): TwoDigits) -> Self {
        value
    }
}

impl TryFrom<u8> for TwoDigits {
    type Error = ();

    fn try_from(value: u8) -> Result<Self, Self::Error> {
        (value < 100).then(move || TwoDigits(value)).ok_or(())
    }
}

impl ToRgb for TwoDigits {
    fn to_rgb(&self) -> [u8; 3] {
        const STEP: u8 = u8::MAX / 99;
        let value = self.0 * STEP;
        [value, value, value]
    }
}