Struct Grid

Source
pub struct Grid<T: Copy + Clone> { /* private fields */ }
Expand description

Stores the grid values and the cells The grid itself representation is a flatten vector which is transformed for 2D representation when called by the user

The cells are internally manage by a Vec<T>

So to create a grid with 4x4 (collums and rows)

let grid = das_grid::Grid::new(4, 4, 0);
assert_eq!(grid.size(), 16);

Or if you like let’s say a Tetris style grid

let grid = das_grid::Grid::new(10, 20, 0);

// And it will have 200 cells!
assert_eq!(grid.size(), 200);

Implementations§

Source§

impl<T: Copy + Clone> Grid<T>

Source

pub fn new(rows: i32, cols: i32, value: T) -> Self
where T: Clone + Copy,

Creates a grid of size rows x columns with default value passed on the third parameter For example this will generate a 2x2 grid of value 1:

let grid = das_grid::Grid::new(2, 2, 1);
assert_eq!(grid.size(), 4);
Examples found in repository?
examples/custom_values.rs (line 21)
19fn main() -> Result<(), das_grid::GridErr> {
20    // Initialize empty grid
21    let mut g: das_grid::Grid<Pawn> = das_grid::Grid::new(2, 2, Pawn::None);
22
23    // Set the Player on position 5,5
24    g.set((0, 0), &Pawn::Player)?;
25
26    println!("Initial state {:?}\n", g);
27
28    // Move the player to right
29    if let Ok(()) = g.mov_to((0, 0), das_grid::MoveDirection::Right) {
30        // "The pawn on 5,6 is Player"
31        println!("The pawn on 0, 1 is {}\n", g.get((0, 1)).unwrap());
32    }
33
34    println!("End state {:?}\n", g);
35
36    Ok(())
37}
Source

pub fn new_from_vector(rows: i32, cols: i32, vec: Vec<T>) -> Self

Creates a grid from a given vector with quadratic size For example this will generate a 2x2 grid

let mut grid = das_grid::Grid::new_from_vector(2, 2, vec![1, 2, 3, 4]);
assert_eq!(grid.size(), 4);
Source

pub fn stamp_subgrid( &mut self, index: (i32, i32), sub_grid: Grid<T>, ) -> Result<(), GridErr>

Stamps the subgrid into the destiny grid, merging both

If the sub grid is greater than the main grid it return an error of GridErr::SubgridOverflow Or if the dest x, y grid is out of bounds it return error GridErr::OutOfGrid

let mut grid: das_grid::Grid<i32> = das_grid::Grid::new(10, 10, 0);
let sub_grid: das_grid::Grid<i32> = das_grid::Grid::new(2, 2, 1);
assert!(grid.stamp_subgrid((5, 5), sub_grid).is_ok());
assert_eq!(grid.get((5, 5)).unwrap(), &1);
assert_eq!(grid.get((5, 6)).unwrap(), &1);
assert_eq!(grid.get((6, 5)).unwrap(), &1);
assert_eq!(grid.get((6, 6)).unwrap(), &1);
Source

pub fn get_subgrid( &self, index: (i32, i32), rows: i32, cols: i32, ) -> Result<Grid<T>, GridErr>

Creates the a new grid which is a snapshot of the main grid on the given position and size

If the sub grid is greater than the main grid it return an error of GridErr::SubgridOverflow

Or if the dest x, y grid is out of bounds it return error GridErr::OutOfGrid

let mut grid = das_grid::Grid::new_from_vector(4, 4, (1..=16).collect());
let sub_grid = grid.get_subgrid((2, 2), 2, 2).unwrap();
assert_eq!(sub_grid.get_flatten_grid(), vec![11, 12, 15, 16]);
Source

pub fn stamp_subgrid_with_rules<R>( &mut self, index: (i32, i32), sub_grid: Grid<T>, rules: Vec<R>, ) -> Result<(), GridErr>
where R: Fn((i32, i32), &T) -> Result<(), GridErr>,

Stamps the subgrid into the destiny grid, merging both Only if no rule return error

If the sub grid is greater than the main grid it return an error of GridErr::SubgridOverflow

Or if the dest x, y grid is out of bounds it return error GridErr::OutOfGrid

And if a rule some rule failed it will return GridErr::RuleFailed

let mut grid: das_grid::Grid<i32> = das_grid::Grid::new(10, 10, 1);
let sub_grid: das_grid::Grid<i32> = das_grid::Grid::new(2, 2, 1);

let rule_not_1 = |_: (i32, i32), value: &i32| -> Result<(), das_grid::GridErr> {
    if *value == 1 {
        return Err(das_grid::GridErr::RuleFailed);
    }
    Ok(())
};

assert!(grid
    .stamp_subgrid_with_rules((5, 5), sub_grid, vec![rule_not_1])
    .is_err());
Source

pub fn set(&mut self, index: (i32, i32), value: &T) -> Result<(), GridErr>
where T: Copy,

Sets a given value to the position (x, y)

Be careful if the value is out of the bounds of grid it will return an error with the type of GridErr::OutOfGrid

let mut grid = das_grid::Grid::new(2, 2, 1);
assert!(grid.set((0, 0), &1).is_ok());
Examples found in repository?
examples/custom_values.rs (line 24)
19fn main() -> Result<(), das_grid::GridErr> {
20    // Initialize empty grid
21    let mut g: das_grid::Grid<Pawn> = das_grid::Grid::new(2, 2, Pawn::None);
22
23    // Set the Player on position 5,5
24    g.set((0, 0), &Pawn::Player)?;
25
26    println!("Initial state {:?}\n", g);
27
28    // Move the player to right
29    if let Ok(()) = g.mov_to((0, 0), das_grid::MoveDirection::Right) {
30        // "The pawn on 5,6 is Player"
31        println!("The pawn on 0, 1 is {}\n", g.get((0, 1)).unwrap());
32    }
33
34    println!("End state {:?}\n", g);
35
36    Ok(())
37}
Source

pub fn set_with_rules<R>( &mut self, index: (i32, i32), value: &T, rules: Vec<R>, ) -> Result<(), GridErr>
where R: Fn((i32, i32), &T) -> Result<(), GridErr>,

Sets a given value to the position (x, y) Only if no rule return error

let mut grid = das_grid::Grid::new(2, 2, 0);
assert!(grid.set((0, 1), &1).is_ok());

let rule_not_1 = |_: (i32, i32), value: &i32| -> Result<(), das_grid::GridErr> {
    if *value == 1 {
        return Err(das_grid::GridErr::RuleFailed);
    }
    Ok(())
};

assert!(
    grid.set_with_rules((0, 1), &1, vec![rule_not_1])
        .err()
        .unwrap()
        == das_grid::GridErr::RuleFailed
);
Source

pub fn get_mut(&mut self, index: (i32, i32)) -> Result<&mut T, GridErr>

Gets a give value to the position (x, y) as mutable

Be careful if the value is out of the bounds of grid it will return an error with the type of GridErr::OutOfGrid

let mut grid = das_grid::Grid::new(2, 2, 1);
let mut v = grid.get_mut((0, 0)).expect("cannnot get pos at (0, 0)");
*v = 50;
assert_eq!(grid.get((0, 0)).unwrap_or(&0), &50);
Source

pub fn get(&self, index: (i32, i32)) -> Result<&T, GridErr>

Gets a give value to the position (x, y)

Be careful if the value is out of the bounds of grid it will return an error with the type of GridErr::OutOfGrid

let grid = das_grid::Grid::new(2, 2, 1);
let v = grid.get((0, 0));
assert_eq!(v, Ok(&1));
Examples found in repository?
examples/custom_values.rs (line 31)
19fn main() -> Result<(), das_grid::GridErr> {
20    // Initialize empty grid
21    let mut g: das_grid::Grid<Pawn> = das_grid::Grid::new(2, 2, Pawn::None);
22
23    // Set the Player on position 5,5
24    g.set((0, 0), &Pawn::Player)?;
25
26    println!("Initial state {:?}\n", g);
27
28    // Move the player to right
29    if let Ok(()) = g.mov_to((0, 0), das_grid::MoveDirection::Right) {
30        // "The pawn on 5,6 is Player"
31        println!("The pawn on 0, 1 is {}\n", g.get((0, 1)).unwrap());
32    }
33
34    println!("End state {:?}\n", g);
35
36    Ok(())
37}
Source

pub fn mov( &mut self, index: (i32, i32), dest: (i32, i32), ) -> Result<(), GridErr>

Moves a given value from position (x, y) to destiny position (x, y)

Be careful if the value is out of the bounds of grid it will return an error with the type of GridErr::OutOfGrid

let mut grid = das_grid::Grid::new(2, 2, 1);
assert_eq!(grid.mov((0, 0), (1, 1)), Ok(()));
Source

pub fn mov_with_rules<R>( &mut self, index: (i32, i32), dest: (i32, i32), rules: Vec<R>, ) -> Result<(), GridErr>
where R: Fn((i32, i32), &T) -> Result<(), GridErr>,

Moves a given value from position (x, y) to destiny position (x, y) Only if no rule return error

Be careful if the value is out of the bounds of grid it will return an error with the type of GridErr::OutOfGrid

And if a rule some rule failed it will return GridErr::RuleFailed

let mut grid = das_grid::Grid::new(2, 2, 0);
assert!(grid.set((0, 1), &1).is_ok());

let rule_not_1 = |_: (i32, i32), value: &i32| -> Result<(), das_grid::GridErr> {
    if *value == 1 {
        return Err(das_grid::GridErr::RuleFailed);
    }
    Ok(())
};

assert!(
    grid.mov_with_rules((0, 0), (0, 1), vec![rule_not_1])
        .err()
        .unwrap()
        == das_grid::GridErr::RuleFailed
);
Source

pub fn mov_to( &mut self, index: (i32, i32), direction: MoveDirection, ) -> Result<(), GridErr>

Moves a given value from position (x, y) to another position based on the direction

The directions can be Left, Right, Top, Down:

  • DasGrid::MoveDirection::Left, translates to (0, -1)
  • DasGrid::MoveDirection::Right, translates to (0, 1)
  • DasGrid::MoveDirection::Top, translates to (-1, 0)
  • DasGrid::MoveDirection::Down, translates to (1, 0)

Be careful if the value is out of the bounds of grid it will return an error with the type of GridErr::OutOfGrid

let mut grid = das_grid::Grid::new(2, 2, 1);
assert_eq!(grid.mov_to((0, 0), das_grid::MoveDirection::Right), Ok(()));
Examples found in repository?
examples/custom_values.rs (line 29)
19fn main() -> Result<(), das_grid::GridErr> {
20    // Initialize empty grid
21    let mut g: das_grid::Grid<Pawn> = das_grid::Grid::new(2, 2, Pawn::None);
22
23    // Set the Player on position 5,5
24    g.set((0, 0), &Pawn::Player)?;
25
26    println!("Initial state {:?}\n", g);
27
28    // Move the player to right
29    if let Ok(()) = g.mov_to((0, 0), das_grid::MoveDirection::Right) {
30        // "The pawn on 5,6 is Player"
31        println!("The pawn on 0, 1 is {}\n", g.get((0, 1)).unwrap());
32    }
33
34    println!("End state {:?}\n", g);
35
36    Ok(())
37}
Source

pub fn mov_to_with_rules<R>( &mut self, index: (i32, i32), direction: MoveDirection, rules: Vec<R>, ) -> Result<(), GridErr>
where R: Fn((i32, i32), &T) -> Result<(), GridErr>,

Moves a given value from position (x, y) to another position based on the direction Only if no rule return error

if the dest x, y grid is out of bounds it return error GridErr::OutOfGrid

And if a rule some rule failed it will return GridErr::RuleFailed

The directions can be Left, Right, Top, Down:

  • DasGrid::MoveDirection::Left, translates to (0, -1)
  • DasGrid::MoveDirection::Right, translates to (0, 1)
  • DasGrid::MoveDirection::Top, translates to (-1, 0)
  • DasGrid::MoveDirection::Down, translates to (1, 0)

Be careful if the value is out of the bounds of grid it will return an error with the type of GridErr::OutOfGrid

let mut g = das_grid::Grid::new(2, 2, 0);
g.set((0, 1), &1);
let rule_not_1 = |_: (i32, i32), value: &i32| -> Result<(), das_grid::GridErr> {
    if *value == 1 {
        return Err(das_grid::GridErr::RuleFailed);
    }
    Ok(())
};
let ret = g.mov_to_with_rules((0, 0), das_grid::MoveDirection::Right, vec![rule_not_1]);
assert!(ret.is_err());
Source

pub fn size(&self) -> usize

Get the size of grid based on cells length

For instance a 10x10 grid will return the size of 100

let mut grid = das_grid::Grid::new(2, 2, 1);
assert_eq!(grid.size(), 4);
Source

pub fn rows(&self) -> i32

The rows of the grid

let mut grid = das_grid::Grid::new(3, 2, 1);
assert_eq!(grid.rows(), 3);
Source

pub fn cols(&self) -> i32

The cols of the grid

let mut grid = das_grid::Grid::new(3, 2, 1);
assert_eq!(grid.cols(), 2);
Source

pub fn enumerate(&self) -> Vec<(i32, i32)>

Returns the grid as a tuple of (x, y)

let mut grid = das_grid::Grid::new(3, 2, 1);
for (x, y) in grid.enumerate() {
    println!("x {} y {}", x, y);
}
Source

pub fn get_col(&self, col_idx: i32) -> Result<Vec<T>, GridErr>

Returns the type vector with the values from the col

If the col idx is wrong it can return the error GridErr::OutOfGrid

let mut g = das_grid::Grid::new_from_vector(2, 2, vec![1, 2, 3, 4]);
let col = g.get_col(1).unwrap();
assert_eq!(col, vec![2, 4]);
Source

pub fn get_row(&self, row_idx: i32) -> Result<Vec<T>, GridErr>

Returns the type vector with the values from the row

If the row idx is wrong it can return the error GridErr::OutOfGrid

let mut g = das_grid::Grid::new_from_vector(2, 2, vec![1, 2, 3, 4]);
let row = g.get_row(1).unwrap();
assert_eq!(row, vec![3, 4]);
Source

pub fn get_flatten_grid(&self) -> Vec<T>

Returns a clone of the internal representation of the grid

let mut g = das_grid::Grid::new_from_vector(2, 2, vec![1, 2, 3, 4]);
assert_eq!(g.get_flatten_grid(), vec![1,2,3,4]);
Source

pub fn fill_grid(&mut self, value: T)

Fill the grid with the given value

Source

pub fn fill_subgrid( &mut self, index: (i32, i32), rows: i32, cols: i32, value: &T, ) -> Result<Grid<T>, GridErr>

Fills the certain area of the grid with a given value

If the area is greater than the main grid it return an error of GridErr::SubgridOverflow

let mut grid = das_grid::Grid::new_from_vector(4, 4, (1..=16).collect());
grid.fill_subgrid((1, 1), 2, 2, &0);
assert!(grid.get((1, 1)).unwrap() == &0);
assert!(grid.get((1, 2)).unwrap() == &0);
assert!(grid.get((2, 1)).unwrap() == &0);
assert!(grid.get((2, 2)).unwrap() == &0);

Trait Implementations§

Source§

impl<T: Copy + Clone + Display> Debug for Grid<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Copy + Clone> Display for Grid<T>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<T: Copy + Clone> Index<(i32, i32)> for Grid<T>

Source§

type Output = T

The returned type after indexing.
Source§

fn index(&self, index: (i32, i32)) -> &T

Performs the indexing (container[index]) operation. Read more
Source§

impl<T: Copy + Clone> IndexMut<(i32, i32)> for Grid<T>

Source§

fn index_mut(&mut self, index: (i32, i32)) -> &mut T

Performs the mutable indexing (container[index]) operation. Read more
Source§

impl<'a, T: Copy + Clone> IntoIterator for &'a Grid<T>

Source§

type Item = &'a T

The type of the elements being iterated over.
Source§

type IntoIter = Iter<'a, T>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more
Source§

impl<'a, T: Copy + Clone> IntoIterator for &'a mut Grid<T>

Source§

type Item = &'a mut T

The type of the elements being iterated over.
Source§

type IntoIter = IterMut<'a, T>

Which kind of iterator are we turning this into?
Source§

fn into_iter(self) -> Self::IntoIter

Creates an iterator from a value. Read more

Auto Trait Implementations§

§

impl<T> Freeze for Grid<T>
where T: Freeze,

§

impl<T> RefUnwindSafe for Grid<T>
where T: RefUnwindSafe,

§

impl<T> Send for Grid<T>
where T: Send,

§

impl<T> Sync for Grid<T>
where T: Sync,

§

impl<T> Unpin for Grid<T>
where T: Unpin,

§

impl<T> UnwindSafe for Grid<T>
where T: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.