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
//! A generic, dirt-simple, two-dimensional grid.
//!
//! # Coordinates
//! Grid entries are accessed with the `Coord` type, which is of the form
//! (column, row), where column >= 0 and row >= 0.
//!
//! # Vectors
//! Instead of offering pre-defined relational getters/iterators such as
//! `neighbors` or `diagonals`, Gridd provides `Vector`s for users to build
//! their own spatial relationship methods. `Vector`s are just `struct`s with
//! positive or negative `col_offset` and `row_offset` fields, enabling the
//! codification of arbitrary relations.
//!
//! Scalar multiplication is reflexively defined on `Vectors` for `i32`
//! values and addition/subtraction is defined between vectors, each in the
//! traditional manner.
//!
//! # Static Grids
//! Currently, Gridd only supports grids of a fixed size.

use std::ops::{Add, Mul, Sub};

//////////////////////////////////////////////////////////////////////////////
// Type Aliases
//////////////////////////////////////////////////////////////////////////////

/// Coordinates of the form (column, row), where column >= 0 and row >= 0.
pub type Coord = (usize, usize);

//////////////////////////////////////////////////////////////////////////////
// 2D Vectors
//////////////////////////////////////////////////////////////////////////////

/// A two-dimensional vector used to relate grid elements spatially.
#[derive(Clone, Copy, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Vector {
    pub col_offset: i32,
    pub row_offset: i32,
}

impl Add for Vector {
    type Output = Self;

    fn add(self, other: Self) -> Self::Output {
        Self {
            col_offset: self.col_offset + other.col_offset,
            row_offset: self.row_offset + other.row_offset,
        }
    }
}

impl Sub for Vector {
    type Output = Self;

    fn sub(self, other: Self) -> Self::Output {
        Self {
            col_offset: self.col_offset - other.col_offset,
            row_offset: self.row_offset - other.row_offset,
        }
    }
}

impl Mul<i32> for Vector {
    type Output = Self;

    fn mul(self, scalar: i32) -> Self::Output {
        Self {
            col_offset: scalar * self.col_offset,
            row_offset: scalar * self.row_offset,
        }
    }
}

impl Mul<Vector> for i32 {
    type Output = Vector;

    fn mul(self, vec: Vector) -> Self::Output {
        vec * self
    }
}

impl From<(i32, i32)> for Vector {
    fn from((c, r): (i32, i32)) -> Self {
        Self {
            col_offset: c,
            row_offset: r,
        }
    }
}

impl Vector {
    //////////////////////////////////
    // Constants
    //////////////////////////////////

    /// Northern unit vector: (col: +0, row: -1).
    pub const NORTH: Vector = Vector {
        col_offset: 0,
        row_offset: -1,
    };

    /// Eastern unit vector: (col: +1, row: +0).
    pub const EAST: Vector = Vector {
        col_offset: 1,
        row_offset: 0,
    };

    /// Southern unit vector: (col: +0, row: +1).
    pub const SOUTH: Vector = Vector {
        col_offset: 0,
        row_offset: 1,
    };

    /// Western unit vector: (col: -1, row: +0).
    pub const WEST: Vector = Vector {
        col_offset: -1,
        row_offset: 0,
    };

    /// Get the coordinate pointed to by a `Vector` from a given `Coord`.
    ///
    /// Returns `None` when either `Coord` component would be negative.
    ///
    /// # Examples
    ///
    /// ```
    /// use gridd::{Coord, Vector};
    ///
    /// let coord: Coord = (3, 5);
    ///
    /// let v1 = Vector::from((-3, 2));
    /// assert_eq!(Some((0, 7)), v1.rcoord(coord));
    ///
    /// let v2 = Vector::from((-4, 5));
    /// assert_eq!(None, v2.rcoord(coord));
    /// ```
    pub fn rcoord(&self, (col, row): Coord) -> Option<Coord> {
        let c = self.col_offset + (col as i32);
        let r = self.row_offset + (row as i32);

        if c >= 0 && r >= 0 {
            Some((c as usize, r as usize))
        } else {
            None
        }
    }

    //////////////////////////////////
    // Instantiation
    //////////////////////////////////

    /// Create a new `Vector` from the sum of cardinal vectors.
    ///
    /// # Examples
    ///
    /// ```
    /// use gridd::Vector;
    ///
    /// assert_eq!(
    ///     Vector::cardinal_sum(1, 0, 1, 0),
    ///     Vector::NORTH + Vector::SOUTH
    /// );
    ///
    /// assert_eq!(
    ///     Vector::cardinal_sum(0, 2, 0, 3),
    ///     2 * Vector::EAST + 3 * Vector::WEST
    /// );
    /// ```
    pub fn cardinal_sum(n: i32, e: i32, s: i32, w: i32) -> Self {
        Vector::NORTH * n
        + Vector::EAST * e
        + Vector::SOUTH * s
        + Vector::WEST * w
    }
}

//////////////////////////////////////////////////////////////////////////////
// Fixed-Size 2D Grids
//////////////////////////////////////////////////////////////////////////////

/// Two-dimensional, non-resizeable, zero-indexed grid.
#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct StaticGrid<T> {
    col_count: usize,
    row_count: usize,
    data: Vec<T>,
}

impl<T> StaticGrid<T>
where
    T: Copy,
{
    //////////////////////////////////
    // Instantiation
    //////////////////////////////////

    /// Create a new `StaticGrid` populated with a default value.
    pub fn new(col_count: usize, row_count: usize, default: T) -> Self
    {
        let capactiy = row_count * col_count;

        Self {
            col_count: col_count,
            row_count: row_count,
            data: vec![default; capactiy],
        }
    }

    /// Create a new `StaticGrid` in a square shape, populated with a default
    /// value.
    pub fn square(side_len: usize, default: T) -> Self
    {
        Self::new(side_len, side_len, default)
    }

    //////////////////////////////////
    // Other Operations
    //////////////////////////////////

    /// Return a transposition of the grid
    pub fn transpose(&self) -> Self {
        if let Some(&val) = self.get((0, 0)) {
            let mut new_grid = Self::new(self.row_count, self.col_count, val);

            for src_row in 0..self.row_count {
                for src_col in 0..self.col_count {
                    if let Some(&val) = self.get((src_col, src_row)) {
                        new_grid.set((src_row, src_col), val)
                    }
                }
            }

            new_grid
        } else {
            Self {
                col_count: 0,
                row_count: 0,
                data: Vec::new(),
            }
        }
    }
}

impl<T> StaticGrid<T> {
    //////////////////////////////////
    // Utilities
    //////////////////////////////////

    /// Get the flat-vector index from the column and row indices.
    fn flat_index(&self, (col, row): Coord) -> usize {
        col + self.col_count * row
    }

    //////////////////////////////////
    // Get & Set
    //////////////////////////////////

    /// Get a grid's column count.
    pub fn col_count(&self) -> usize {
        self.col_count
    }

    /// Get a grid's row count.
    pub fn row_count(&self) -> usize {
        self.row_count
    }

    /// Get an immutable reference to a cell's value.
    pub fn get(&self, coord: Coord) -> Option<&T>
    {
        if self.contains(coord) {
            let index = self.flat_index(coord);

            Some(&self.data[index])
        } else {
            None
        }
    }

    /// Get a mutable reference to a cell's value.
    pub fn get_mut(&mut self, coord: Coord) -> Option<&mut T> {
        if self.contains(coord) {
            let index = self.flat_index(coord);

            Some(&mut self.data[index])
        } else {
            None
        }
    }

    /// Get an immutable reference to a cell's value offset from an anchor.
    pub fn rget(&self, anchor: Coord, vec: Vector) -> Option<&T> {
        match vec.rcoord(anchor) {
            Some(coord) => self.get(coord),
            _ => None,
        }
    }

    /// Get a mutable reference to a cell's value offset from an anchor.
    pub fn rget_mut(&mut self, anchor: Coord, vec: Vector) -> Option<&mut T> {
        match vec.rcoord(anchor) {
            Some(coord) => self.get_mut(coord),
            _ => None,
        }
    }

    /// Set a cell's value.
    pub fn set(&mut self, coord: Coord, new_val: T) {
        match self.get_mut(coord) {
            Some(val) => {
                *val = new_val;
            }
            None => (),
        }
    }

    //////////////////////////////////
    // Boolean Operations
    //////////////////////////////////

    /// Determine if a coordinate is within the grid
    pub fn contains(&self, (col, row): Coord) -> bool {
        col < self.col_count && row < self.row_count
    }
}

//////////////////////////////////////////////////////////////////////////////
// Unit Tests
//////////////////////////////////////////////////////////////////////////////

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_get_mut() {
        let mut grid = StaticGrid::new(1, 1, 'a');
        let value = grid.get_mut((0, 0)).unwrap();

        assert_eq!(&'a', value);
        *value = 'b';
        assert_eq!(&'b', value);
    }

    #[test]
    fn test_get_set() {
        let mut grid = StaticGrid::new(5, 5, 'a');

        assert_eq!(Some(&'a'), grid.get((2, 3)));
        assert_eq!(Some(&'a'), grid.get((3, 3)));
        assert_eq!(Some(&'a'), grid.get((3, 4)));

        grid.set((2, 3), 'b');
        grid.set((3, 3), 'c');
        grid.set((3, 4), 'd');

        assert_eq!(Some(&'b'), grid.get((2, 3)));
        assert_eq!(Some(&'c'), grid.get((3, 3)));
        assert_eq!(Some(&'d'), grid.get((3, 4)));
    }

    #[test]
    fn test_rget() {
        let mut grid = StaticGrid::new(5, 5, 'a');

        assert_eq!(Some(&'a'), grid.get((2, 3)));

        grid.set((2, 3), 'b');

        assert_eq!(Some(&'b'), grid.rget((2, 4), Vector::NORTH));
        assert_eq!(Some(&mut 'b'), grid.rget_mut((2, 4), Vector::NORTH));
    }

    #[test]
    fn test_transpose() {
        let src_col = 3;
        let src_row = 4;

        let mut grid = StaticGrid::new(src_col, src_row, (0, 0));

        for i in 0..src_col {
            for j in 0..src_row {
                grid.set((i, j), (i, j));
            }
        }

        let tgrid = grid.transpose();

        assert_eq!(4, tgrid.col_count());
        assert_eq!(3, tgrid.row_count());

        for i in 0..src_col {
            for j in 0..src_row {
                assert_eq!(tgrid.get((j, i)), grid.get((i, j)));
            }
        }
    }
}