Skip to content

Add try_into_owned_nocopy method #1022

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 2 commits into from
Nov 7, 2021
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
94 changes: 85 additions & 9 deletions src/data_traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ use std::ptr::NonNull;
use alloc::sync::Arc;
use alloc::vec::Vec;

use crate::{ArrayBase, CowRepr, Dimension, OwnedArcRepr, OwnedRepr, RawViewRepr, ViewRepr};
use crate::{
ArcArray, Array, ArrayBase, CowRepr, Dimension, OwnedArcRepr, OwnedRepr, RawViewRepr, ViewRepr,
};

/// Array representation trait.
///
Expand Down Expand Up @@ -97,16 +99,25 @@ pub unsafe trait Data: RawData {
/// Converts the array to a uniquely owned array, cloning elements if necessary.
#[doc(hidden)]
#[allow(clippy::wrong_self_convention)]
fn into_owned<D>(self_: ArrayBase<Self, D>) -> ArrayBase<OwnedRepr<Self::Elem>, D>
fn into_owned<D>(self_: ArrayBase<Self, D>) -> Array<Self::Elem, D>
where
Self::Elem: Clone,
D: Dimension;

/// Converts the array into `Array<A, D>` if this is possible without
/// cloning the array elements. Otherwise, returns `self_` unchanged.
#[doc(hidden)]
fn try_into_owned_nocopy<D>(
self_: ArrayBase<Self, D>,
) -> Result<Array<Self::Elem, D>, ArrayBase<Self, D>>
where
D: Dimension;

/// Return a shared ownership (copy on write) array based on the existing one,
/// cloning elements if necessary.
#[doc(hidden)]
#[allow(clippy::wrong_self_convention)]
fn to_shared<D>(self_: &ArrayBase<Self, D>) -> ArrayBase<OwnedArcRepr<Self::Elem>, D>
fn to_shared<D>(self_: &ArrayBase<Self, D>) -> ArcArray<Self::Elem, D>
where
Self::Elem: Clone,
D: Dimension,
Expand Down Expand Up @@ -259,7 +270,7 @@ where
}

unsafe impl<A> Data for OwnedArcRepr<A> {
fn into_owned<D>(mut self_: ArrayBase<Self, D>) -> ArrayBase<OwnedRepr<Self::Elem>, D>
fn into_owned<D>(mut self_: ArrayBase<Self, D>) -> Array<Self::Elem, D>
where
A: Clone,
D: Dimension,
Expand All @@ -273,8 +284,29 @@ unsafe impl<A> Data for OwnedArcRepr<A> {
}
}

fn try_into_owned_nocopy<D>(
self_: ArrayBase<Self, D>,
) -> Result<Array<Self::Elem, D>, ArrayBase<Self, D>>
where
D: Dimension,
{
match Arc::try_unwrap(self_.data.0) {
Ok(owned_data) => unsafe {
// Safe because the data is equivalent.
Ok(ArrayBase::from_data_ptr(owned_data, self_.ptr)
.with_strides_dim(self_.strides, self_.dim))
},
Err(arc_data) => unsafe {
// Safe because the data is equivalent; we're just
// reconstructing `self_`.
Err(ArrayBase::from_data_ptr(OwnedArcRepr(arc_data), self_.ptr)
.with_strides_dim(self_.strides, self_.dim))
},
}
}

#[allow(clippy::wrong_self_convention)]
fn to_shared<D>(self_: &ArrayBase<Self, D>) -> ArrayBase<OwnedArcRepr<Self::Elem>, D>
fn to_shared<D>(self_: &ArrayBase<Self, D>) -> ArcArray<Self::Elem, D>
where
Self::Elem: Clone,
D: Dimension,
Expand Down Expand Up @@ -327,13 +359,23 @@ unsafe impl<A> RawDataMut for OwnedRepr<A> {

unsafe impl<A> Data for OwnedRepr<A> {
#[inline]
fn into_owned<D>(self_: ArrayBase<Self, D>) -> ArrayBase<OwnedRepr<Self::Elem>, D>
fn into_owned<D>(self_: ArrayBase<Self, D>) -> Array<Self::Elem, D>
where
A: Clone,
D: Dimension,
{
self_
}

#[inline]
fn try_into_owned_nocopy<D>(
self_: ArrayBase<Self, D>,
) -> Result<Array<Self::Elem, D>, ArrayBase<Self, D>>
where
D: Dimension,
{
Ok(self_)
}
}

unsafe impl<A> DataMut for OwnedRepr<A> {}
Expand Down Expand Up @@ -383,13 +425,22 @@ unsafe impl<'a, A> RawData for ViewRepr<&'a A> {
}

unsafe impl<'a, A> Data for ViewRepr<&'a A> {
fn into_owned<D>(self_: ArrayBase<Self, D>) -> ArrayBase<OwnedRepr<Self::Elem>, D>
fn into_owned<D>(self_: ArrayBase<Self, D>) -> Array<Self::Elem, D>
where
Self::Elem: Clone,
D: Dimension,
{
self_.to_owned()
}

fn try_into_owned_nocopy<D>(
self_: ArrayBase<Self, D>,
) -> Result<Array<Self::Elem, D>, ArrayBase<Self, D>>
where
D: Dimension,
{
Err(self_)
}
}

unsafe impl<'a, A> RawDataClone for ViewRepr<&'a A> {
Expand Down Expand Up @@ -428,13 +479,22 @@ unsafe impl<'a, A> RawDataMut for ViewRepr<&'a mut A> {
}

unsafe impl<'a, A> Data for ViewRepr<&'a mut A> {
fn into_owned<D>(self_: ArrayBase<Self, D>) -> ArrayBase<OwnedRepr<Self::Elem>, D>
fn into_owned<D>(self_: ArrayBase<Self, D>) -> Array<Self::Elem, D>
where
Self::Elem: Clone,
D: Dimension,
{
self_.to_owned()
}

fn try_into_owned_nocopy<D>(
self_: ArrayBase<Self, D>,
) -> Result<Array<Self::Elem, D>, ArrayBase<Self, D>>
where
D: Dimension,
{
Err(self_)
}
}

unsafe impl<'a, A> DataMut for ViewRepr<&'a mut A> {}
Expand Down Expand Up @@ -590,7 +650,7 @@ where

unsafe impl<'a, A> Data for CowRepr<'a, A> {
#[inline]
fn into_owned<D>(self_: ArrayBase<CowRepr<'a, A>, D>) -> ArrayBase<OwnedRepr<Self::Elem>, D>
fn into_owned<D>(self_: ArrayBase<CowRepr<'a, A>, D>) -> Array<Self::Elem, D>
where
A: Clone,
D: Dimension,
Expand All @@ -604,6 +664,22 @@ unsafe impl<'a, A> Data for CowRepr<'a, A> {
},
}
}

fn try_into_owned_nocopy<D>(
self_: ArrayBase<Self, D>,
) -> Result<Array<Self::Elem, D>, ArrayBase<Self, D>>
where
D: Dimension,
{
match self_.data {
CowRepr::View(_) => Err(self_),
CowRepr::Owned(data) => unsafe {
// safe because the data is equivalent so ptr, dims remain valid
Ok(ArrayBase::from_data_ptr(data, self_.ptr)
.with_strides_dim(self_.strides, self_.dim))
},
}
}
}

unsafe impl<'a, A> DataMut for CowRepr<'a, A> where A: Clone {}
Expand Down
28 changes: 28 additions & 0 deletions src/impl_methods.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,34 @@ where
S::into_owned(self)
}

/// Converts the array into `Array<A, D>` if this is possible without
/// cloning the array elements. Otherwise, returns `self` unchanged.
///
/// ```
/// use ndarray::{array, rcarr2, ArcArray2, Array2};
///
/// // Reference-counted, clone-on-write `ArcArray`.
/// let a: ArcArray2<_> = rcarr2(&[[1., 2.], [3., 4.]]);
/// {
/// // Another reference to the same data.
/// let b: ArcArray2<_> = a.clone();
/// // Since there are two references to the same data, `.into_owned()`
/// // would require cloning the data, so `.try_into_owned_nocopy()`
/// // returns `Err`.
/// assert!(b.try_into_owned_nocopy().is_err());
/// }
/// // Here, since the second reference has been dropped, the `ArcArray`
/// // can be converted into an `Array` without cloning the data.
/// let unique: Array2<_> = a.try_into_owned_nocopy().unwrap();
/// assert_eq!(unique, array![[1., 2.], [3., 4.]]);
/// ```
pub fn try_into_owned_nocopy(self) -> Result<Array<A, D>, Self>
where
S: Data,
{
S::try_into_owned_nocopy(self)
}

/// Turn the array into a shared ownership (copy on write) array,
/// without any copying.
pub fn into_shared(self) -> ArcArray<A, D>
Expand Down