1 | use crate::{ |
2 | grid::config::{Entity, Position}, |
3 | settings::object::Object, |
4 | }; |
5 | |
6 | /// Cell denotes a particular cell on a [`Table`]. |
7 | /// |
8 | /// For example such table has 4 cells. |
9 | /// Which indexes are (0, 0), (0, 1), (1, 0), (1, 1). |
10 | /// |
11 | /// ```text |
12 | /// ┌───┬───┐ |
13 | /// │ 0 │ 1 │ |
14 | /// ├───┼───┤ |
15 | /// │ 1 │ 2 │ |
16 | /// └───┴───┘ |
17 | /// ``` |
18 | /// |
19 | /// [`Table`]: crate::Table |
20 | #[derive (Debug, Default, PartialEq, Eq, PartialOrd, Ord)] |
21 | pub struct Cell(usize, usize); |
22 | |
23 | impl Cell { |
24 | /// Create new cell structure. |
25 | pub fn new(row: usize, col: usize) -> Self { |
26 | Self(row, col) |
27 | } |
28 | } |
29 | |
30 | impl From<Position> for Cell { |
31 | fn from((row: usize, col: usize): Position) -> Self { |
32 | Self(row, col) |
33 | } |
34 | } |
35 | |
36 | impl<I> Object<I> for Cell { |
37 | type Iter = EntityOnce; |
38 | |
39 | fn cells(&self, _: &I) -> Self::Iter { |
40 | EntityOnce::new(entity:Some(Entity::Cell(self.0, self.1))) |
41 | } |
42 | } |
43 | |
44 | impl<I> Object<I> for Position { |
45 | type Iter = EntityOnce; |
46 | |
47 | fn cells(&self, _: &I) -> Self::Iter { |
48 | EntityOnce::new(entity:Some(Entity::Cell(self.0, self.1))) |
49 | } |
50 | } |
51 | |
52 | /// An [`Iterator`] which returns an entity once. |
53 | #[derive (Debug)] |
54 | pub struct EntityOnce { |
55 | entity: Option<Entity>, |
56 | } |
57 | |
58 | impl EntityOnce { |
59 | pub(crate) const fn new(entity: Option<Entity>) -> Self { |
60 | Self { entity } |
61 | } |
62 | } |
63 | |
64 | impl Iterator for EntityOnce { |
65 | type Item = Entity; |
66 | |
67 | fn next(&mut self) -> Option<Self::Item> { |
68 | self.entity.take() |
69 | } |
70 | } |
71 | |