Skip to content

Commit 63062d3

Browse files
ssande7bluss
authored andcommitted
Add convenience functions for reserving space for rows/columns in Array2
1 parent aa077bf commit 63062d3

1 file changed

Lines changed: 39 additions & 0 deletions

File tree

src/impl_owned_array.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,44 @@ impl<A> Array<A, Ix2>
251251
{
252252
self.append(Axis(1), column.insert_axis(Axis(1)))
253253
}
254+
255+
/// Reserve capacity to grow array by at least `additional` rows.
256+
///
257+
/// Existing elements of `array` are untouched and the backing storage is grown by
258+
/// calling the underlying `reserve` method of the `OwnedRepr`.
259+
///
260+
/// This is useful when pushing or appending repeatedly to an array to avoid multiple
261+
/// allocations.
262+
///
263+
/// ```rust
264+
/// use ndarray::Array2;
265+
/// let mut a = Array2::<i32>::zeros((2,4));
266+
/// a.reserve_rows(1000);
267+
/// assert!(a.into_raw_vec().capacity() >= 4*1002);
268+
/// ```
269+
pub fn reserve_rows(&mut self, additional: usize)
270+
{
271+
self.reserve(Axis(0), additional);
272+
}
273+
274+
/// Reserve capacity to grow array by at least `additional` columns.
275+
///
276+
/// Existing elements of `array` are untouched and the backing storage is grown by
277+
/// calling the underlying `reserve` method of the `OwnedRepr`.
278+
///
279+
/// This is useful when pushing or appending repeatedly to an array to avoid multiple
280+
/// allocations.
281+
///
282+
/// ```rust
283+
/// use ndarray::Array2;
284+
/// let mut a = Array2::<i32>::zeros((2,4));
285+
/// a.reserve_columns(1000);
286+
/// assert!(a.into_raw_vec().capacity() >= 2*1002);
287+
/// ```
288+
pub fn reserve_columns(&mut self, additional: usize)
289+
{
290+
self.reserve(Axis(1), additional);
291+
}
254292
}
255293

256294
impl<A, D> Array<A, D>
@@ -761,6 +799,7 @@ where D: Dimension
761799
/// let mut a = Array3::<i32>::zeros((0,2,4));
762800
/// a.reserve(Axis(0), 1000);
763801
/// assert!(a.into_raw_vec().capacity() >= 2*4*1000);
802+
/// ```
764803
pub fn reserve(&mut self, axis: Axis, additional: usize)
765804
where D: RemoveAxis
766805
{

0 commit comments

Comments
 (0)