Skip to content

Commit e85a1cf

Browse files
committed
FIX: Fix try_append_array when appending empty arrays
Fix a problem with appending empty arrays (found by ndarray-rand's quickcheck thank you). The try_append_array method was returning a tad too early in this case.
1 parent 6fe0b5d commit e85a1cf

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

src/impl_owned_array.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -205,15 +205,21 @@ impl<A, D> Array<A, D>
205205
}
206206

207207
let len_to_append = array.len();
208-
if len_to_append == 0 {
209-
return Ok(());
210-
}
211208

212209
let array_shape = array.raw_dim();
213210
let mut res_dim = self.raw_dim();
214211
res_dim[axis.index()] += array_shape[axis.index()];
215212
let new_len = dimension::size_of_shape_checked(&res_dim)?;
216213

214+
if len_to_append == 0 {
215+
// There are no elements to append and shapes are compatible:
216+
// either the dimension increment is zero, or there is an existing
217+
// zero in another axis in self.
218+
debug_assert_eq!(self.len(), new_len);
219+
self.dim = res_dim;
220+
return Ok(());
221+
}
222+
217223
let self_is_empty = self.is_empty();
218224

219225
// array must be empty or have `axis` as the outermost (longest stride) axis

tests/append.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,3 +195,22 @@ fn test_append_middle_axis() {
195195
a.try_append_array(Axis(1), Array::from_iter(12..24).into_shape((3, 2, 2)).unwrap().view()).unwrap();
196196
println!("{:?}", a);
197197
}
198+
199+
#[test]
200+
fn test_append_zero_size() {
201+
{
202+
let mut a = Array::<i32, _>::zeros((0, 0));
203+
a.try_append_array(Axis(0), aview2(&[[]])).unwrap();
204+
a.try_append_array(Axis(0), aview2(&[[]])).unwrap();
205+
assert_eq!(a.len(), 0);
206+
assert_eq!(a.shape(), &[2, 0]);
207+
}
208+
209+
{
210+
let mut a = Array::<i32, _>::zeros((0, 0));
211+
a.try_append_array(Axis(1), ArrayView::from(&[]).into_shape((0, 1)).unwrap()).unwrap();
212+
a.try_append_array(Axis(1), ArrayView::from(&[]).into_shape((0, 1)).unwrap()).unwrap();
213+
assert_eq!(a.len(), 0);
214+
assert_eq!(a.shape(), &[0, 2]);
215+
}
216+
}

0 commit comments

Comments
 (0)