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
16 D: Dimension,
17{
18 /// Returns `true` iff the array is the view (borrowed) variant.
19 pub fn is_view(&self) -> bool {
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 self.data.is_owned()
26 }
27}
28
29impl<'a, A, D> From<ArrayView<'a, A, D>> for CowArray<'a, A, D>
30where
31 D: Dimension,
32{
33 fn from(view: ArrayView<'a, A, D>) -> CowArray<'a, A, D> {
34 // safe because equivalent data
35 unsafe {
36 ArrayBase::from_data_ptr(CowRepr::View(view.data), view.ptr)
37 .with_strides_dim(view.strides, view.dim)
38 }
39 }
40}
41
42impl<'a, A, D> From<Array<A, D>> for CowArray<'a, A, D>
43where
44 D: Dimension,
45{
46 fn from(array: Array<A, D>) -> CowArray<'a, A, D> {
47 // safe because equivalent data
48 unsafe {
49 ArrayBase::from_data_ptr(CowRepr::Owned(array.data), array.ptr)
50 .with_strides_dim(array.strides, array.dim)
51 }
52 }
53}
54
55impl<'a, A, Slice: ?Sized> From<&'a Slice> for CowArray<'a, A, Ix1>
56where
57 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 Self::from(ArrayView1::from(slice))
72 }
73}
74
75impl<'a, A, S, D> From<&'a ArrayBase<S, D>> for CowArray<'a, A, D>
76where
77 S: Data<Elem = A>,
78 D: Dimension,
79{
80 /// Create a read-only clone-on-write view of the array.
81 fn from(array: &'a ArrayBase<S, D>) -> Self {
82 Self::from(array.view())
83 }
84}