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
211
212
213
214
215
216
217
218
use core::fmt::{self, Display, Formatter};

use crate::location::{Column, Component as LocComponent, Location, LocationLike, Row};
use crate::range::{
    ColumnRange, ColumnRangeError, ComponentRange, RangeError, RowRange, RowRangeError,
};
use crate::vector::{Columns, Component as VecComponent, Rows, Vector, VectorLike};

/// High-level trait implementing grid sizes and boundary checking.
///
/// This trait doesn't provide any direct grid functionality, but instead
/// provides the bounds checking which is generic to all of the different
/// kinds of grid.
pub trait BaseGridBounds {
    /// Get the dimensions of the grid, as a [`Vector`].
    fn dimensions(&self) -> Vector;

    /// Return the root location (ie, the top left) of the grid. For most grids,
    /// this is (0, 0), but some grids may include negatively indexed locations,
    /// or even offsets. All valid locations have `location >= root`.
    #[inline]
    fn root(&self) -> Location {
        Location::zero()
    }
}

impl<G: BaseGridBounds + ?Sized> BaseGridBounds for &G {
    #[inline]
    fn dimensions(&self) -> Vector {
        G::dimensions(self)
    }

    #[inline]
    fn root(&self) -> Location {
        G::root(self)
    }
}

impl<G: BaseGridBounds + ?Sized> BaseGridBounds for &mut G {
    #[inline]
    fn dimensions(&self) -> Vector {
        G::dimensions(self)
    }

    #[inline]
    fn root(&self) -> Location {
        G::root(self)
    }
}

pub trait GridBounds: BaseGridBounds {
    /// Get the outer root of the grid; that is, the location for which all
    /// valid locations in the grid have `row < outer.row && column < outer.column`
    #[inline]
    fn outer_root(&self) -> Location {
        self.root() + self.dimensions()
    }

    /// Get the height of the grid in [`Rows`].
    #[inline]
    fn num_rows(&self) -> Rows {
        self.dimensions().rows
    }

    /// Get the width of the grid, in [`Columns`].
    #[inline]
    fn num_columns(&self) -> Columns {
        self.dimensions().columns
    }

    /// Get the height or width of this grid.
    #[inline]
    fn dimension<C: VecComponent>(&self) -> C {
        self.dimensions().get_component()
    }

    /// Return the index of the topmost row of this grid. For most grids,
    /// this is 0, but some grids may include negatively indexed locations,
    /// or even offsets.
    #[inline]
    fn root_row(&self) -> Row {
        self.root().row
    }

    /// Return the index of the leftmost column of this grid. For most grids,
    /// this is 0, but some grids may include negatively indexed locations,
    /// or even offsets.
    #[inline]
    fn root_column(&self) -> Column {
        self.root().column
    }

    /// Return the index of the leftmost column or topmost row of this grid.
    #[inline]
    fn root_component<C: LocComponent>(&self) -> C {
        self.root().get_component()
    }

    /// Get a Range over the row or column indexes
    #[inline]
    fn range<C: LocComponent>(&self) -> ComponentRange<C> {
        ComponentRange::span(self.root_component(), self.dimension())
    }

    /// A range iterator over all the column indexes in this grid
    #[inline]
    fn row_range(&self) -> RowRange {
        self.range()
    }

    /// A range iterator over all the row indexes in this grid
    #[inline]
    fn column_range(&self) -> ColumnRange {
        self.range()
    }

    /// Check that a Row or a Column is inside the bounds described by this Grid.
    #[inline]
    fn check_component<C: LocComponent>(&self, c: C) -> Result<C, RangeError<C>> {
        self.range().check(c)
    }

    #[inline]
    fn check_row(&self, row: impl Into<Row>) -> Result<Row, RowRangeError> {
        self.check_component(row.into())
    }

    #[inline]
    fn check_column(&self, column: impl Into<Column>) -> Result<Column, ColumnRangeError> {
        self.check_component(column.into())
    }

    #[inline]
    fn component_in_bounds<C: LocComponent>(&self, c: C) -> bool {
        self.check_component(c).is_ok()
    }

    #[inline]
    fn row_in_bounds(&self, row: impl Into<Row>) -> bool {
        self.component_in_bounds(row.into())
    }

    #[inline]
    fn column_in_bounds(&self, column: impl Into<Column>) -> bool {
        self.component_in_bounds(column.into())
    }

    /// Check that a location is inside the bounds of this grid.
    ///
    /// Returns the Location if successful, or an error describing the boundary
    /// error if not. This function is intended to help write more expressive code;
    /// ie, `grid.check_location(loc).and_then(|loc| ...)`. Note that the
    /// safe grid interfaces are guarenteed to be bounds checked, where relevant.
    #[inline]
    fn check_location(&self, location: impl LocationLike) -> Result<Location, BoundsError> {
        let location = location.as_location();
        self.check_component(location.row)?;
        self.check_component(location.column)?;
        Ok(location)
    }

    /// Returns true if a locaton is inside the bounds of this grid.
    #[inline]
    fn location_in_bounds(&self, location: impl LocationLike) -> bool {
        self.check_location(location).is_ok()
    }
}

impl<G: BaseGridBounds> GridBounds for G {}

/// An out-of-bounds error for a Location on a grid
///
/// This error is returned by methods that perform bounds checking to indicate
/// a failed bounds check. It includes the specific boundary that was violated.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum BoundsError {
    /// The location's `Row` was out of bounds
    Row(RowRangeError),

    /// The location's `Column` was out of bounds
    Column(ColumnRangeError),
}

impl From<RowRangeError> for BoundsError {
    #[inline]
    fn from(err: RowRangeError) -> Self {
        BoundsError::Row(err)
    }
}

impl From<ColumnRangeError> for BoundsError {
    #[inline]
    fn from(err: ColumnRangeError) -> Self {
        BoundsError::Column(err)
    }
}

impl Display for BoundsError {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        match self {
            BoundsError::Row(err) => write!(f, "Row out of bounds: {}", err),
            BoundsError::Column(err) => write!(f, "Column out of bounds: {}", err),
        }
    }
}

// TODO: Add this when we figure out how to make it compatible with no_std
/*
impl<T: Component> Error for BoundsError {
    fn source(&self) -> Option<&(Error + 'static)> {
        match self {
            BoundsError::Row(err) => Some(err),
            BoundsError::Column(err) => Some(err),
        }
    }
}
*/