tabled/settings/object/
cell.rs

1use 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, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
21pub struct Cell(usize, usize);
22
23impl Cell {
24    /// Create new cell structure.
25    pub fn new(row: usize, col: usize) -> Self {
26        Self(row, col)
27    }
28}
29
30impl From<Position> for Cell {
31    fn from(pos: Position) -> Self {
32        Self(pos.row, pos.col)
33    }
34}
35
36impl From<(usize, usize)> for Cell {
37    fn from(pos: (usize, usize)) -> Self {
38        Self(pos.0, pos.1)
39    }
40}
41
42impl From<Cell> for Position {
43    fn from(Cell(row, col): Cell) -> Self {
44        Position::new(row, col)
45    }
46}
47
48impl<I> Object<I> for Cell {
49    type Iter = EntityOnce;
50
51    fn cells(&self, _: &I) -> Self::Iter {
52        EntityOnce::new(Some(Entity::Cell(self.0, self.1)))
53    }
54}
55
56impl<I> Object<I> for Position {
57    type Iter = EntityOnce;
58
59    fn cells(&self, _: &I) -> Self::Iter {
60        EntityOnce::new(Some(Entity::Cell(self.row, self.col)))
61    }
62}
63
64impl<I> Object<I> for (usize, usize) {
65    type Iter = EntityOnce;
66
67    fn cells(&self, _: &I) -> Self::Iter {
68        EntityOnce::new(Some(Entity::Cell(self.0, self.1)))
69    }
70}
71
72/// An [`Iterator`] which returns an entity once.
73#[derive(Debug)]
74pub struct EntityOnce {
75    entity: Option<Entity>,
76}
77
78impl EntityOnce {
79    pub(crate) const fn new(entity: Option<Entity>) -> Self {
80        Self { entity }
81    }
82}
83
84impl Iterator for EntityOnce {
85    type Item = Entity;
86
87    fn next(&mut self) -> Option<Self::Item> {
88        self.entity.take()
89    }
90}