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, D> CowArray<'_, 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 {
37 ArrayBase::from_data_ptr(CowRepr::View(view.data), view.parts.ptr)
38 .with_strides_dim(view.parts.strides, view.parts.dim)
39 }
40 }
41}
42
43impl<'a, A, D> From<Array<A, D>> for CowArray<'a, A, D>
44where D: Dimension
45{
46 fn from(array: Array<A, D>) -> CowArray<'a, A, D>
47 {
48 // safe because equivalent data
49 unsafe {
50 ArrayBase::from_data_ptr(CowRepr::Owned(array.data), array.parts.ptr)
51 .with_strides_dim(array.parts.strides, array.parts.dim)
52 }
53 }
54}
55
56impl<'a, A, Slice: ?Sized> From<&'a Slice> for CowArray<'a, A, Ix1>
57where Slice: AsRef<[A]>
58{
59 /// Create a one-dimensional clone-on-write view of the data in `slice`.
60 ///
61 /// **Panics** if the slice length is greater than [`isize::MAX`].
62 ///
63 /// ```
64 /// use ndarray::{array, CowArray};
65 ///
66 /// let array = CowArray::from(&[1., 2., 3., 4.]);
67 /// assert!(array.is_view());
68 /// assert_eq!(array, array![1., 2., 3., 4.]);
69 /// ```
70 fn from(slice: &'a Slice) -> Self
71 {
72 Self::from(ArrayView1::from(slice))
73 }
74}
75
76impl<'a, A, S, D> From<&'a ArrayBase<S, D>> for CowArray<'a, A, D>
77where
78 S: Data<Elem = A>,
79 D: Dimension,
80{
81 /// Create a read-only clone-on-write view of the array.
82 fn from(array: &'a ArrayBase<S, D>) -> Self
83 {
84 Self::from(array.view())
85 }
86}