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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
pub mod adapters;

use core::fmt::Debug;
use core::iter::FusedIterator;
use core::marker::PhantomData;
use core::ops::Index;

use crate::location::component::{
    ColumnRange, ColumnRangeError, Range as IndexRange, RangeError, RowRange, RowRangeError,
};
use crate::location::{Column, Component as LocComponent, Location, Range as LocRange, Row};
use crate::vector::{Columns, Component as VecComponent, Rows, Vector};

/// 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.
///
/// Note for implementors:
pub trait GridBounds {
    /// Get the dimensions of the grid, as a [`Vector`]. This value MUST be
    /// const for any given grid.
    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. This value MUST be const for any given grid.
    fn root(&self) -> Location {
        Location::new(0, 0)
    }
}

impl<'a, G: GridBounds + ?Sized> GridBounds for &'a G {
    fn dimensions(&self) -> Vector {
        (**self).dimensions()
    }
    fn root(&self) -> Location {
        (**self).root()
    }
}

impl<'a, G: GridBounds + ?Sized> GridBounds for &'a mut G {
    fn dimensions(&self) -> Vector {
        (**self).dimensions()
    }
    fn root(&self) -> Location {
        (**self).root()
    }
}

pub trait GridBoundsExt: GridBounds {
    /// Get the height of the grid in [`Rows`]. This value MUST be const for
    /// any given grid.
    fn num_rows(&self) -> Rows {
        self.dimensions().rows
    }

    /// Get the width of the grid, in [`Columns`]. This value MUST be const for
    /// any given grid.
    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. This value MUST be const for any given grid.
    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. This value MUST be const for any given grid.
    fn root_column(&self) -> Column {
        self.root().column
    }

    /// Return the index of the leftmost row or column 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) -> IndexRange<C> {
        IndexRange::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 component_in_bounds<C: LocComponent>(&self, c: C) -> bool {
        self.range().in_bounds(c)
    }

    /// 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.
    fn check_location(&self, loc: impl Into<Location>) -> Result<Location, LocationRangeError> {
        let loc = loc.into();
        self.check_component(loc.row)?;
        self.check_component(loc.column)?;
        Ok(loc)
    }

    /// Returns true if a locaton is inside the bounds of this grid.
    fn location_in_bounds(&self, location: impl Into<Location>) -> bool {
        self.check_location(location).is_ok()
    }
}

impl<G: GridBounds> GridBoundsExt 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 LocationRangeError {
    /// The location's `Row` was out of bounds
    Row(RowRangeError),

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

impl From<RowRangeError> for LocationRangeError {
    fn from(err: RowRangeError) -> Self {
        LocationRangeError::Row(err)
    }
}

impl From<ColumnRangeError> for LocationRangeError {
    fn from(err: ColumnRangeError) -> Self {
        LocationRangeError::Column(err)
    }
}

pub trait BaseGrid: GridBoundsExt {
    type Item;

    /// Get a reference to a cell, without doing bounds checking. Implementors
    /// of this method are allowed to assume that bounds checking has already
    /// been performed on the location.
    unsafe fn get_unchecked(&self, loc: &Location) -> &Self::Item;
}

impl<'a, G: BaseGrid> BaseGrid for &'a G {
    type Item = G::Item;

    unsafe fn get_unchecked(&self, loc: &Location) -> &Self::Item {
        (**self).get_unchecked(loc)
    }
}

impl<'a, G: BaseGrid> BaseGrid for &'a mut G {
    type Item = G::Item;

    unsafe fn get_unchecked(&self, loc: &Location) -> &Self::Item {
        (**self).get_unchecked(loc)
    }
}

/// View methods for a Grid, aimed at providing support for iterating over rows,
/// columns, and cells inside of those views.
pub trait Grid: BaseGrid {
    /// Get a reference to a cell in a grid. Returns an error if the location
    /// is out of bounds with the specific boundary violation.
    fn get(&self, location: impl Into<Location>) -> Result<&Self::Item, LocationRangeError> {
        self.check_location(location)
            .map(move |loc| unsafe { self.get_unchecked(&loc) })
    }

    // Get a view of a grid, over its rows or columns
    fn view<T: LocComponent>(&self) -> View<Self, T> {
        View::new(self)
    }

    /// Get a view of a grid's rows
    fn rows(&self) -> RowsView<Self> {
        self.view()
    }

    /// Get a view of a grid's columns
    fn columns(&self) -> ColumnsView<Self> {
        self.view()
    }

    /// Get a view of a single row or column in a grid, without bounds checking that
    /// row or column index.
    unsafe fn single_view_unchecked<T: LocComponent>(&self, index: T) -> SingleView<Self, T> {
        SingleView::new_unchecked(self, index)
    }

    /// Get a view of a single row in a grid, without bounds checking that row's index
    unsafe fn row_unchecked(&self, row: impl Into<Row>) -> RowView<Self> {
        self.single_view_unchecked(row.into())
    }

    /// Get a view of a single column in a grid, without bounds checking that column's index
    unsafe fn column_unchecked(&self, column: impl Into<Column>) -> ColumnView<Self> {
        self.single_view_unchecked(column.into())
    }

    /// Get a view of a single row or column in a grid. Returns an error if the index of the
    /// row or column is out of bounds for the grid.
    fn single_view<T: LocComponent>(&self, index: T) -> Result<SingleView<Self, T>, RangeError<T>> {
        SingleView::new(self, index)
    }

    /// Get a view of a single row in a grid. Returns an error if the index of the row is
    /// out of bounds for the grid.
    fn row(&self, row: impl Into<Row>) -> Result<RowView<Self>, RowRangeError> {
        self.single_view(row.into())
    }

    /// Get a view of a single column in a grid. Returns an error if the index of the column
    /// is out of bounds for the grid.
    fn column(&self, column: impl Into<Column>) -> Result<ColumnView<Self>, ColumnRangeError> {
        self.single_view(column.into())
    }
}

impl<G: BaseGrid> Grid for G {}

/// A view of the Rows or Columns in a grid.
///
/// This struct provides a row- or column-major view of a grid. For instance,
/// a `View<MyGrid, Row>` is a View of all of the rows in MyGrid.
///
///
pub struct View<'a, G: Grid + ?Sized, T: LocComponent> {
    grid: &'a G,
    index: PhantomData<T>,
}

impl<'a, G: Grid + ?Sized, T: LocComponent> View<'a, G, T> {
    fn new(grid: &'a G) -> Self {
        Self {
            grid,
            index: PhantomData,
        }
    }

    pub unsafe fn get_unchecked(&self, index: T) -> SingleView<G, T> {
        SingleView::new_unchecked(self.grid, index)
    }

    pub fn get(&self, index: impl Into<T>) -> Result<SingleView<G, T>, RangeError<T>> {
        SingleView::new(self.grid, index.into())
    }

    pub fn range(&self) -> IndexRange<T> {
        self.grid.range()
    }

    pub fn iter(
        &self,
    ) -> impl Iterator<Item = SingleView<'a, G, T>>
                 + DoubleEndedIterator
                 + FusedIterator
                 + ExactSizeIterator
                 + Debug
                 + Clone {
        let grid = self.grid;
        self.range()
            .map(move |index| unsafe { SingleView::new_unchecked(grid, index) })
    }
}

// TODO: impl Index for GridView. Requires Higher Kinded Lifetimes, because
// Index currently requires an &'a T, but we want to return a GridSingleView<'a, T>
// TODO: IntoIterator

pub type RowsView<'a, G> = View<'a, G, Row>;
pub type ColumnsView<'a, G> = View<'a, G, Column>;

// Implementor notes: a GridSingleView's index field is guaranteed to have been
// bounds checked against the grid. Therefore, we provide unsafe constructors, and
// then freely use unsafe accessors in the safe interface.
pub struct SingleView<'a, G: Grid + ?Sized, T: LocComponent> {
    grid: &'a G,
    index: T,
}

impl<'a, G: Grid + ?Sized, T: LocComponent> SingleView<'a, G, T> {
    unsafe fn new_unchecked(grid: &'a G, index: T) -> Self {
        Self { grid, index }
    }

    fn new(grid: &'a G, index: T) -> Result<Self, RangeError<T>> {
        grid.check_component(index)
            .map(move |index| unsafe { Self::new_unchecked(grid, index) })
    }

    pub fn index(&self) -> T {
        self.index
    }

    pub unsafe fn get_unchecked(&self, cross: T::Converse) -> &'a G::Item {
        self.grid.get_unchecked(&self.index.combine(cross))
    }

    pub fn get(
        &self,
        cross: impl Into<T::Converse>,
    ) -> Result<&'a G::Item, RangeError<T::Converse>> {
        self.grid
            .check_component(cross.into())
            .map(move |cross| unsafe { self.get_unchecked(cross) })
    }

    /// Get the locations associated with this view
    pub fn range(&self) -> LocRange<T> {
        LocRange::new(self.index, self.grid.range())
    }

    pub fn iter(
        &self,
    ) -> impl Iterator<Item = &'a G::Item>
                 + DoubleEndedIterator
                 + FusedIterator
                 + ExactSizeIterator
                 + Debug
                 + Clone {
        let grid = self.grid;
        self.range()
            .map(move |loc| unsafe { grid.get_unchecked(&loc) })
    }

    pub fn with_locations(
        &self,
    ) -> impl Iterator<Item = (Location, &'a G::Item)>
                 + DoubleEndedIterator
                 + FusedIterator
                 + ExactSizeIterator
                 + Debug
                 + Clone {
        let grid = self.grid;
        self.range()
            .map(move |loc| (loc, unsafe { grid.get_unchecked(&loc) }))
    }

    pub fn with_component(
        &self,
    ) -> impl Iterator<Item = (T::Converse, &'a G::Item)>
                 + DoubleEndedIterator
                 + FusedIterator
                 + ExactSizeIterator
                 + Debug
                 + Clone {
        let grid = self.grid;
        let index = self.index;
        self.grid.range().map(move |cross: T::Converse| {
            (cross, unsafe {
                grid.get_unchecked(&(cross.combine(index)))
            })
        })
    }
}

impl<'a, G: Grid + ?Sized, T: LocComponent> Index<T::Converse> for SingleView<'a, G, T> {
    type Output = G::Item;

    fn index(&self, idx: T::Converse) -> &G::Item {
        // TODO: insert error message once RangeError implements Error + Display
        self.get(idx)
            .unwrap_or_else(|_err| panic!("{} out of range", T::name()))
    }
}

// TODO: IntoIterator

pub type RowView<'a, G> = SingleView<'a, G, Row>;
pub type ColumnView<'a, G> = SingleView<'a, G, Column>;

pub trait BaseGridMut: BaseGrid {
    /// Get a mutable reference to a cell, without doing bounds checking. Implementors
    /// of this method are allowed to assume that bounds checking has already been
    /// performed on the location.
    unsafe fn get_unchecked_mut(&mut self, loc: &Location) -> &mut Self::Item;

    /// Set the value of a cell in a location, without bounds checking the location.
    unsafe fn set_unchecked(&mut self, loc: &Location, value: Self::Item) {
        *self.get_unchecked_mut(loc) = value;
    }
}

impl<'a, G: BaseGridMut> BaseGridMut for &'a mut G {
    unsafe fn get_unchecked_mut(&mut self, loc: &Location) -> &mut Self::Item {
        (**self).get_unchecked_mut(loc)
    }

    unsafe fn set_unchecked(&mut self, loc: &Location, value: Self::Item) {
        (**self).set_unchecked(loc, value)
    }
}

pub trait GridMut: BaseGridMut {
    fn get_mut(
        &mut self,
        location: impl Into<Location>,
    ) -> Result<&mut Self::Item, LocationRangeError> {
        self.check_location(location.into())
            .map(move |loc| unsafe { self.get_unchecked_mut(&loc) })
    }

    fn set(
        &mut self,
        location: impl Into<Location>,
        value: Self::Item,
    ) -> Result<(), LocationRangeError> {
        self.check_location(location.into())
            .map(move |loc| unsafe { self.set_unchecked(&loc, value) })
    }
}

impl<G: BaseGridMut> GridMut for G {}