Skip to content

Add into_scalar method for Array0 #535

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

Merged
merged 1 commit into from
Nov 14, 2018
Merged
Show file tree
Hide file tree
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
39 changes: 39 additions & 0 deletions src/impl_owned_array.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,44 @@
use imp_prelude::*;

/// Methods specific to `Array0`.
///
/// ***See also all methods for [`ArrayBase`]***
///
/// [`ArrayBase`]: struct.ArrayBase.html
impl<A> Array<A, Ix0> {
/// Returns the single element in the array without cloning it.
///
/// ```
/// use ndarray::{arr0, Array0};
///
/// // `Foo` doesn't implement `Clone`.
/// #[derive(Debug, Eq, PartialEq)]
/// struct Foo;
///
/// let array: Array0<Foo> = arr0(Foo);
/// let scalar: Foo = array.into_scalar();
/// assert_eq!(scalar, Foo);
/// ```
pub fn into_scalar(mut self) -> A {
let size = ::std::mem::size_of::<A>();
if size == 0 {
// Any index in the `Vec` is fine since all elements are identical.
self.data.0.remove(0)
} else {
// Find the index in the `Vec` corresponding to `self.ptr`.
// (This is necessary because the element in the array might not be
// the first element in the `Vec`, such as if the array was created
// by `array![1, 2, 3, 4].slice_move(s![2])`.)
let first = self.ptr as usize;
let base = self.data.0.as_ptr() as usize;
let index = (first - base) / size;
debug_assert_eq!((first - base) % size, 0);
// Remove the element at the index and return it.
self.data.0.remove(index)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gnarly but it works fine. Maybe a comment to explain that the len of the Vec might be bigger than the array's current len

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, I've added a explanatory comment. If someone changes the implementation in the future, the test will also help catch this edge case.

}
}
}

/// Methods specific to `Array`.
///
/// ***See also all methods for [`ArrayBase`]***
Expand Down
9 changes: 5 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -855,11 +855,11 @@ pub type Ixs = isize;
/// </tr>
/// </table>
///
/// ### Conversions Between Arrays and `Vec`s/Slices
/// ### Conversions Between Arrays and `Vec`s/Slices/Scalars
///
/// This is a table of the safe conversions between arrays and `Vec`s/slices.
/// Note that some of the return values are actually `Result`/`Option` wrappers
/// around the indicated output types.
/// This is a table of the safe conversions between arrays and
/// `Vec`s/slices/scalars. Note that some of the return values are actually
/// `Result`/`Option` wrappers around the indicated output types.
///
/// Input | Output | Methods
/// ------|--------|--------
Expand All @@ -875,6 +875,7 @@ pub type Ixs = isize;
/// `&mut ArrayBase<S: DataMut, D>` | `&mut [A]` | [`.as_slice_mut()`](#method.as_slice_mut)<sup>[2](#req_contig_std)</sup>, [`.as_slice_memory_order_mut()`](#method.as_slice_memory_order_mut)<sup>[3](#req_contig)</sup>
/// `ArrayView<A, D>` | `&[A]` | [`.into_slice()`](type.ArrayView.html#method.into_slice)
/// `ArrayViewMut<A, D>` | `&mut [A]` | [`.into_slice()`](type.ArrayViewMut.html#method.into_slice)
/// `Array0<A>` | `A` | [`.into_scalar()`](type.Array.html#method.into_scalar)
///
/// <sup><a name="into_raw_vec">1</a></sup>Returns the data in memory order.
///
Expand Down
15 changes: 15 additions & 0 deletions tests/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -928,6 +928,21 @@ fn as_slice_memory_order()
assert!(a != b, "{:?} != {:?}", a, b);
}

#[test]
fn array0_into_scalar() {
// With this kind of setup, the `Array`'s pointer is not the same as the
// underlying `Vec`'s pointer.
let a: Array0<i32> = array![4, 5, 6, 7].into_subview(Axis(0), 2);
assert_ne!(a.as_ptr(), a.into_raw_vec().as_ptr());
// `.into_scalar()` should still work correctly.
let a: Array0<i32> = array![4, 5, 6, 7].into_subview(Axis(0), 2);
assert_eq!(a.into_scalar(), 6);

// It should work for zero-size elements too.
let a: Array0<()> = array![(), (), (), ()].into_subview(Axis(0), 2);
assert_eq!(a.into_scalar(), ());
}

#[test]
fn owned_array1() {
let mut a = Array::from_vec(vec![1, 2, 3, 4]);
Expand Down