| 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 From<Cell> for Position { |
| 37 | fn from(Cell(row: usize, col: usize): Cell) -> Self { |
| 38 | (row, col) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | impl<I> Object<I> for Cell { |
| 43 | type Iter = EntityOnce; |
| 44 | |
| 45 | fn cells(&self, _: &I) -> Self::Iter { |
| 46 | EntityOnce::new(entity:Some(Entity::Cell(self.0, self.1))) |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | impl<I> Object<I> for Position { |
| 51 | type Iter = EntityOnce; |
| 52 | |
| 53 | fn cells(&self, _: &I) -> Self::Iter { |
| 54 | EntityOnce::new(entity:Some(Entity::Cell(self.0, self.1))) |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | /// An [`Iterator`] which returns an entity once. |
| 59 | #[derive (Debug)] |
| 60 | pub struct EntityOnce { |
| 61 | entity: Option<Entity>, |
| 62 | } |
| 63 | |
| 64 | impl EntityOnce { |
| 65 | pub(crate) const fn new(entity: Option<Entity>) -> Self { |
| 66 | Self { entity } |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | impl Iterator for EntityOnce { |
| 71 | type Item = Entity; |
| 72 | |
| 73 | fn next(&mut self) -> Option<Self::Item> { |
| 74 | self.entity.take() |
| 75 | } |
| 76 | } |
| 77 | |