diff --git a/src/impl_ref_types.rs b/src/impl_ref_types.rs index 92e916887..6907ddcd8 100644 --- a/src/impl_ref_types.rs +++ b/src/impl_ref_types.rs @@ -21,17 +21,20 @@ //! To mitigate these problems, `ndarray` also provides `AsRef` and `AsMut` implementations as follows: //! 1. `ArrayBase` implements `AsRef` to `RawRef` and `LayoutRef` when `S: RawData` //! 2. `ArrayBase` implements `AsMut` to `RawRef` when `S: RawDataMut` -//! 3. `ArrayBase` implements `AsMut` to `LayoutRef` unconditionally -//! 4. `ArrayRef` implements `AsMut` to `RawRef` and `LayoutRef` unconditionally -//! 5. `RawRef` implements `AsMut` to `LayoutRef` -//! 6. `RawRef` and `LayoutRef` implement `AsMut` to themselves +//! 3. `ArrayBase` implements `AsRef` and `AsMut` to `LayoutRef` unconditionally +//! 4. `ArrayRef` implements `AsRef` and `AsMut` to `RawRef` and `LayoutRef` unconditionally +//! 5. `RawRef` implements `AsRef` and `AsMut` to `LayoutRef` +//! 6. `RawRef` and `LayoutRef` implement `AsRef` and `AsMut` to themselves //! //! This allows users to write a single method or trait implementation that takes `T: AsRef>` //! or `T: AsRef>` and have that functionality work on any of the relevant array types. -use core::ops::{Deref, DerefMut}; +use core::{ + borrow::{Borrow, BorrowMut}, + ops::{Deref, DerefMut}, +}; -use crate::{ArrayBase, ArrayRef, Data, DataMut, Dimension, LayoutRef, RawData, RawDataMut, RawRef}; +use crate::{Array, ArrayBase, ArrayRef, Data, DataMut, Dimension, LayoutRef, RawData, RawDataMut, RawRef}; // D1: &ArrayBase -> &ArrayRef when data is safe to read impl Deref for ArrayBase @@ -286,3 +289,59 @@ impl Clone for LayoutRef } impl Copy for LayoutRef {} + +impl Borrow> for ArrayBase +where S: RawData +{ + fn borrow(&self) -> &RawRef + { + self.as_ref() + } +} + +impl BorrowMut> for ArrayBase +where S: RawDataMut +{ + fn borrow_mut(&mut self) -> &mut RawRef + { + self.as_mut() + } +} + +impl Borrow> for ArrayBase +where S: Data +{ + fn borrow(&self) -> &ArrayRef + { + &**self + } +} + +impl BorrowMut> for ArrayBase +where + S: DataMut, + D: Dimension, +{ + fn borrow_mut(&mut self) -> &mut ArrayRef + { + &mut **self + } +} + +impl ToOwned for ArrayRef +where + A: Clone, + D: Dimension, +{ + type Owned = Array; + + fn to_owned(&self) -> Self::Owned + { + self.to_owned() + } + + fn clone_into(&self, target: &mut Array) + { + target.zip_mut_with(self, |tgt, src| tgt.clone_from(src)); + } +}