Skip to content

Commit 6f8058b

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 504f168 commit 6f8058b

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

src/impl_owned_array.rs

+9-3
Original file line numberDiff line numberDiff line change
@@ -201,15 +201,21 @@ impl<A, D> Array<A, D>
201201
}
202202

203203
let len_to_append = array.len();
204-
if len_to_append == 0 {
205-
return Ok(());
206-
}
207204

208205
let array_shape = array.raw_dim();
209206
let mut res_dim = self.raw_dim();
210207
res_dim[axis.index()] += array_shape[axis.index()];
211208
let new_len = dimension::size_of_shape_checked(&res_dim)?;
212209

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

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

tests/append.rs

+19
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)