tenferro_tensor/view.rs
1//! Input adapter shared by all operation families (the #2552 `AsView` grammar).
2//!
3//! [`AsView`] turns any tensor input into a borrowed [`TensorRead`] without
4//! copying element data. [`Repr`] says whether results should come back
5//! dtype-erased ([`Erased`]) or statically typed ([`Typed`]).
6
7use std::marker::PhantomData;
8
9use crate::{
10 Error, Tensor, TensorRead, TensorScalar, TensorWrite, TypedTensor, TypedTensorView,
11 TypedTensorWrite,
12};
13
14mod sealed {
15 pub trait Sealed {}
16}
17
18/// A representation of tensor values: dtype-erased or statically typed.
19///
20/// # Examples
21///
22/// ```
23/// use tenferro_tensor::{Erased, Repr, Tensor, Typed};
24///
25/// let a = Tensor::from_vec_col_major(vec![1], vec![1.0_f64])?;
26/// let b = Tensor::from_vec_col_major(vec![1], vec![1.0_f64])?;
27/// let erased = <Erased as Repr>::wrap_value(a)?;
28/// let typed = <Typed<f64> as Repr>::wrap_value(b)?;
29/// assert_eq!(erased.shape(), typed.shape());
30/// # Ok::<(), tenferro_tensor::Error>(())
31/// ```
32pub trait Repr: sealed::Sealed {
33 /// The value type: `Tensor` or `TypedTensor<T>`.
34 type Value;
35 /// The writable target type: `TensorWrite<'a>` or `TypedTensorWrite<'a, T>`.
36 type Write<'a>;
37
38 /// Wrap an erased result in this representation. Typed representations
39 /// perform a checked downcast.
40 ///
41 /// # Errors
42 ///
43 /// Returns [`Error::Internal`] when a typed representation receives a
44 /// tensor of another dtype.
45 ///
46 /// # Examples
47 ///
48 /// ```
49 /// use tenferro_tensor::{Repr, Tensor, Typed};
50 ///
51 /// let t = Tensor::from_vec_col_major(vec![1], vec![1.0_f64])?;
52 /// assert!(<Typed<f64> as Repr>::wrap_value(t.duplicate()?).is_ok());
53 /// assert!(<Typed<f32> as Repr>::wrap_value(t).is_err());
54 /// # Ok::<(), tenferro_tensor::Error>(())
55 /// ```
56 fn wrap_value(t: Tensor) -> crate::Result<Self::Value>;
57
58 /// Erase a writable target to [`TensorWrite`]. Metadata only.
59 ///
60 /// # Examples
61 ///
62 /// ```
63 /// use tenferro_tensor::{Erased, Repr, Tensor, TensorWrite};
64 ///
65 /// let mut t = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?;
66 /// let write = TensorWrite::from_tensor(&mut t);
67 /// let erased = <Erased as Repr>::erase_write(write);
68 /// assert_eq!(erased.shape(), &[2]);
69 /// # Ok::<(), tenferro_tensor::Error>(())
70 /// ```
71 fn erase_write<'a>(w: Self::Write<'a>) -> TensorWrite<'a>;
72}
73
74/// The dtype-erased representation.
75///
76/// # Examples
77///
78/// ```
79/// use tenferro_tensor::{Erased, Repr, Tensor};
80///
81/// let t = Tensor::from_vec_col_major(vec![1], vec![1.0_f64])?;
82/// let same = <Erased as Repr>::wrap_value(t)?;
83/// assert_eq!(same.shape(), &[1]);
84/// # Ok::<(), tenferro_tensor::Error>(())
85/// ```
86#[derive(Debug, Clone, Copy)]
87pub struct Erased;
88
89/// The statically typed representation for scalar `T`.
90///
91/// # Examples
92///
93/// ```
94/// use tenferro_tensor::{Repr, Tensor, Typed};
95///
96/// let t = Tensor::from_vec_col_major(vec![1], vec![1.0_f64])?;
97/// let typed = <Typed<f64> as Repr>::wrap_value(t)?;
98/// assert_eq!(typed.shape(), &[1]);
99/// # Ok::<(), tenferro_tensor::Error>(())
100/// ```
101pub struct Typed<T>(PhantomData<fn() -> T>);
102
103impl<T> std::fmt::Debug for Typed<T> {
104 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
105 f.write_str("Typed")
106 }
107}
108
109impl<T> Clone for Typed<T> {
110 fn clone(&self) -> Self {
111 *self
112 }
113}
114
115impl<T> Copy for Typed<T> {}
116
117impl<T> Default for Typed<T> {
118 fn default() -> Self {
119 Self(PhantomData)
120 }
121}
122
123impl sealed::Sealed for Erased {}
124impl<T: TensorScalar> sealed::Sealed for Typed<T> {}
125
126impl Repr for Erased {
127 type Value = Tensor;
128 type Write<'a> = TensorWrite<'a>;
129
130 fn wrap_value(t: Tensor) -> crate::Result<Tensor> {
131 Ok(t)
132 }
133
134 fn erase_write<'a>(w: Self::Write<'a>) -> TensorWrite<'a> {
135 w
136 }
137}
138
139impl<T: TensorScalar> Repr for Typed<T> {
140 type Value = TypedTensor<T>;
141 type Write<'a> = TypedTensorWrite<'a, T>;
142
143 fn wrap_value(t: Tensor) -> crate::Result<TypedTensor<T>> {
144 let actual = t.dtype();
145 t.into_typed::<T>().map_err(|_| {
146 Error::Internal(format!(
147 "checked downcast failed: result dtype {actual:?} is not {:?}",
148 T::dtype()
149 ))
150 })
151 }
152
153 fn erase_write<'a>(w: Self::Write<'a>) -> TensorWrite<'a> {
154 w.into_tensor_write()
155 }
156}
157
158/// Any tensor input that can be read as a borrowed view without copying.
159///
160/// # Examples
161///
162/// ```
163/// use tenferro_tensor::{AsView, Tensor, TensorRead, TypedTensor, TypedTensorView};
164///
165/// let tensor = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?;
166/// let typed = TypedTensor::<f64>::from_vec_col_major(vec![2], vec![1.0, 2.0])?;
167/// let read = TensorRead::from_tensor(&tensor);
168///
169/// assert_eq!(tensor.as_read().shape(), typed.as_read().shape());
170/// assert_eq!(read.as_read().dtype(), typed.as_read().dtype());
171/// assert_eq!((&&tensor).as_read().shape(), &[2]);
172///
173/// let data = [1.0_f64, 2.0];
174/// let view = TypedTensorView::from_col_major(&[2], &data)?;
175/// assert_eq!(view.as_read().shape(), &[2]);
176/// assert_eq!(view.as_read().as_slice::<f64>()?.as_ptr(), data.as_ptr());
177///
178/// // No element data is copied.
179/// assert_eq!(
180/// tensor.as_read().as_slice::<f64>()?.as_ptr(),
181/// tensor.as_read().as_slice::<f64>()?.as_ptr(),
182/// );
183/// assert_eq!(
184/// typed.as_read().as_slice::<f64>()?.as_ptr(),
185/// typed.as_slice()?.as_ptr(),
186/// );
187/// # Ok::<(), tenferro_tensor::Error>(())
188/// ```
189pub trait AsView: sealed::Sealed {
190 /// The representation results take for this input.
191 type Repr: Repr;
192
193 /// Borrow this input as a [`TensorRead`]. Metadata only; never copies
194 /// element data.
195 ///
196 /// # Examples
197 ///
198 /// ```
199 /// use tenferro_tensor::{AsView, Tensor};
200 ///
201 /// let t = Tensor::from_vec_col_major(vec![2], vec![1.0_f64, 2.0])?;
202 /// let read = t.as_read();
203 /// assert_eq!(read.shape(), &[2]);
204 /// assert_eq!(read.as_slice::<f64>()?, &[1.0, 2.0]);
205 /// # Ok::<(), tenferro_tensor::Error>(())
206 /// ```
207 fn as_read(&self) -> TensorRead<'_>;
208}
209
210impl sealed::Sealed for Tensor {}
211impl sealed::Sealed for TensorRead<'_> {}
212impl<T: TensorScalar> sealed::Sealed for TypedTensor<T> {}
213impl<T: TensorScalar> sealed::Sealed for TypedTensorView<'_, T> {}
214impl<X: sealed::Sealed + ?Sized> sealed::Sealed for &X {}
215
216impl AsView for Tensor {
217 type Repr = Erased;
218
219 fn as_read(&self) -> TensorRead<'_> {
220 TensorRead::from_tensor(self)
221 }
222}
223
224impl AsView for TensorRead<'_> {
225 type Repr = Erased;
226
227 fn as_read(&self) -> TensorRead<'_> {
228 // `TensorRead` only holds borrows, so cloning copies metadata.
229 self.clone()
230 }
231}
232
233impl<T: TensorScalar> AsView for TypedTensor<T> {
234 type Repr = Typed<T>;
235
236 fn as_read(&self) -> TensorRead<'_> {
237 T::tensor_read(self)
238 }
239}
240
241impl<T: TensorScalar> AsView for TypedTensorView<'_, T> {
242 type Repr = Typed<T>;
243
244 fn as_read(&self) -> TensorRead<'_> {
245 // The default `DynRank`/`Dynamic` view maps to `TensorView` directly,
246 // so unlike `into_tensor_read` this conversion cannot fail.
247 TensorRead::from_view(T::tensor_view(self.clone()))
248 }
249}
250
251impl<X: AsView + ?Sized> AsView for &X {
252 type Repr = X::Repr;
253
254 fn as_read(&self) -> TensorRead<'_> {
255 (**self).as_read()
256 }
257}
258
259#[cfg(test)]
260mod tests;