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
use super::{
codes::{Code, LETTER_MASK},
item::Item,
tile::Tile,
};
use crate::error::Error;
use std::convert::TryFrom;
#[derive(Debug, Copy, Clone, PartialEq, Default)]
pub struct Cell(Option<Tile>);
impl Item for Cell {
fn code(&self) -> Code {
self.0.map_or(0, |tile| tile.code())
}
}
impl Cell {
pub const EMPTY: Self = Self(None);
fn new(code: Code) -> Cell {
if code == 0 {
Cell(None)
} else {
Cell(Some(Tile::new(code)))
}
}
pub fn from_tile(tile: Tile) -> Cell {
Cell::new(tile.code())
}
pub fn tile(&self) -> Option<Tile> {
self.0
}
pub fn is_empty(&self) -> bool {
self.0.is_none()
}
pub fn to_letter(self) -> Cell {
Cell::new(self.code() & LETTER_MASK)
}
}
impl TryFrom<Code> for Cell {
type Error = Error;
fn try_from(code: Code) -> Result<Self, Self::Error> {
match code {
0 | 1..=31 | 65..=95 => Ok(Self::new(code)),
_ => Err(Self::Error::InvalidTileCode(code)),
}
}
}
impl Into<Code> for Cell {
fn into(self) -> Code {
self.code()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_to_letter() {
let cell = Cell::new(65);
assert_eq!(cell.code(), 65);
assert_eq!(cell.to_letter().code(), 1);
}
}