Skip to content

Commit

Permalink
Add convenience functions for reserving space for rows/columns in Array2
Browse files Browse the repository at this point in the history
  • Loading branch information
ssande7 authored and bluss committed Mar 10, 2024
1 parent 96755bf commit caf7de3
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/impl_owned_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,42 @@ impl<A> Array<A, Ix2> {
{
self.append(Axis(1), column.insert_axis(Axis(1)))
}

/// Reserve capacity to grow array by at least `additional` rows.
///
/// Existing elements of `array` are untouched and the backing storage is grown by
/// calling the underlying `reserve` method of the `OwnedRepr`.
///
/// This is useful when pushing or appending repeatedly to an array to avoid multiple
/// allocations.
///
/// ```rust
/// use ndarray::Array2;
/// let mut a = Array2::<i32>::zeros((2,4));
/// a.reserve_rows(1000);
/// assert!(a.into_raw_vec().capacity() >= 4*1002);
/// ```
pub fn reserve_rows(&mut self, additional: usize) {
self.reserve(Axis(0), additional);
}

/// Reserve capacity to grow array by at least `additional` columns.
///
/// Existing elements of `array` are untouched and the backing storage is grown by
/// calling the underlying `reserve` method of the `OwnedRepr`.
///
/// This is useful when pushing or appending repeatedly to an array to avoid multiple
/// allocations.
///
/// ```rust
/// use ndarray::Array2;
/// let mut a = Array2::<i32>::zeros((2,4));
/// a.reserve_columns(1000);
/// assert!(a.into_raw_vec().capacity() >= 2*1002);
/// ```
pub fn reserve_columns(&mut self, additional: usize) {
self.reserve(Axis(1), additional);
}
}

impl<A, D> Array<A, D>
Expand Down Expand Up @@ -666,6 +702,7 @@ impl<A, D> Array<A, D>
/// let mut a = Array3::<i32>::zeros((0,2,4));
/// a.reserve(Axis(0), 1000);
/// assert!(a.into_raw_vec().capacity() >= 2*4*1000);
/// ```
pub fn reserve(&mut self, axis: Axis, additional: usize)
where
D: RemoveAxis,
Expand Down

0 comments on commit caf7de3

Please sign in to comment.