ndarray/impl_cow.rs
1// Copyright 2019 ndarray developers.
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9use crate::imp_prelude::*;
10
11/// Methods specific to `CowArray`.
12///
13/// ***See also all methods for [`ArrayBase`]***
14impl<'a, A, D> CowArray<'a, A, D>
15where D: Dimension
16{
17 /// Returns `true` iff the array is the view (borrowed) variant.
18 pub fn is_view(&self) -> bool
19 {
20 self.data.is_view()
21 }
22
23 /// Returns `true` iff the array is the owned variant.
24 pub fn is_owned(&self) -> bool
25 {
26 self.data.is_owned()
27 }
28}
29
30impl<'a, A, D> From<ArrayView<'a, A, D>> for CowArray<'a, A, D>
31where D: Dimension
32{
33 fn from(view: ArrayView<'a, A, D>) -> CowArray<'a, A, D>
34 {
35 // safe because equivalent data
36 unsafe { ArrayBase::from_data_ptr(CowRepr::View(view.data), view.ptr).with_strides_dim(view.strides, view.dim) }
37 }
38}
39
40impl<'a, A, D> From<Array<A, D>> for CowArray<'a, A, D>
41where D: Dimension
42{
43 fn from(array: Array<A, D>) -> CowArray<'a, A, D>
44 {
45 // safe because equivalent data
46 unsafe {
47 ArrayBase::from_data_ptr(CowRepr::Owned(array.data), array.ptr).with_strides_dim(array.strides, array.dim)
48 }
49 }
50}
51
52impl<'a, A, Slice: ?Sized> From<&'a Slice> for CowArray<'a, A, Ix1>
53where Slice: AsRef<[A]>
54{
55 /// Create a one-dimensional clone-on-write view of the data in `slice`.
56 ///
57 /// **Panics** if the slice length is greater than [`isize::MAX`].
58 ///
59 /// ```
60 /// use ndarray::{array, CowArray};
61 ///
62 /// let array = CowArray::from(&[1., 2., 3., 4.]);
63 /// assert!(array.is_view());
64 /// assert_eq!(array, array![1., 2., 3., 4.]);
65 /// ```
66 fn from(slice: &'a Slice) -> Self
67 {
68 Self::from(ArrayView1::from(slice))
69 }
70}
71
72impl<'a, A, S, D> From<&'a ArrayBase<S, D>> for CowArray<'a, A, D>
73where
74 S: Data<Elem = A>,
75 D: Dimension,
76{
77 /// Create a read-only clone-on-write view of the array.
78 fn from(array: &'a ArrayBase<S, D>) -> Self
79 {
80 Self::from(array.view())
81 }
82}