Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implemented with_capacity #53

Merged
merged 1 commit into from
Aug 31, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 67 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -412,6 +412,30 @@ impl<T> Grid<T> {
}
}

/// Initialises an empty Grid with the capacity to store `cols * rows` elements.
/// Similar to `Vec::with_capacity`.
///
/// # Panics
///
/// Panics if `rows * cols > usize::MAX` or if `rows * cols * size_of::<T>() > isize::MAX`
pub fn with_capacity(rows: usize, cols: usize) -> Self {
Self::with_capacity_and_order(rows, cols, Order::default())
}

/// Same as [`with_capacity`](Self::with_capacity) but with a specified [`Order`]
///
/// # Panics
///
/// Panics if `rows * cols > usize::MAX` or if `rows * cols * size_of::<T>() > isize::MAX`
pub fn with_capacity_and_order(rows: usize, cols: usize, order: Order) -> Self {
Self {
data: Vec::with_capacity(rows.checked_mul(cols).unwrap()),
cols: 0,
rows: 0,
order,
}
}

/// Returns a grid from a vector with a given column length.
/// The length of `vec` must be a multiple of `cols`.
///
Expand Down Expand Up @@ -3023,6 +3047,49 @@ mod test {
test_grid(&grid, 0, 0, Order::ColumnMajor, &[]);
}

#[test]
fn with_capacity() {
// doesn't impl Default
struct Foo();

let grid: Grid<Foo> = Grid::with_capacity(20, 20);
assert!(grid.is_empty());
assert_eq!(grid.order(), Order::default());
}

#[test]
fn with_capacity_and_order() {
// doesn't impl Default
struct Foo();

let grid: Grid<Foo> = Grid::with_capacity_and_order(20, 20, Order::ColumnMajor);
assert!(grid.is_empty());
assert_eq!(grid.order(), Order::ColumnMajor);
}

#[test]
#[should_panic]
#[allow(clippy::should_panic_without_expect)]
fn with_capacity_panics_internal() {
// doesn't impl Default
struct Foo();

let _grid: Grid<Foo> = Grid::with_capacity_and_order(usize::MAX, 2, Order::RowMajor);
}

#[test]
#[should_panic]
#[allow(clippy::should_panic_without_expect)]
fn with_capacity_panics_vec() {
let rows: usize = isize::MAX.try_into().expect("isize::MAX is positive");
assert!(
core::mem::size_of::<u8>() * rows < usize::MAX,
"shows that panic is from Vec::with_capacity, not internal check"
);

let _grid: Grid<u8> = Grid::with_capacity_and_order(rows, 2, Order::RowMajor);
}

#[test]
fn get() {
let grid = Grid::from_vec_with_order(vec![1, 2], 2, Order::RowMajor);
Expand Down
Loading