dlt/tensor/
scalar.rs

1use crate::tensor::*;
2use crate::units::*;
3use crate::tensor::element::*;
4use std::marker::PhantomData;
5
6pub type Scalar<E: TensorElement, D> = Tensor<E, D, 1, 1, 1>;
7
8impl<E: TensorElement, D> Scalar<E, D> {
9    // Require TensorElement to provide an EPSILON constant.
10    pub const EPSILON: Scalar<E, D> = Scalar {
11        data: [E::EPSILON],
12        _phantom: PhantomData,
13    };
14
15    // Construct a Scalar from a basic f64 value.
16    pub fn from<U: Unit<Dimension = D>>(value: E) -> Self {
17        Scalar {
18            data: [U::to_base(value.into()).into()],
19            _phantom: PhantomData,
20        }
21    }
22
23    // Return the raw underlying element.
24    pub fn raw(&self) -> E {
25        self.data[0]
26    }
27
28    // Convert the raw element into any type implementing From<E>.
29    pub fn raw_as<T: From<E>>(&self) -> T {
30        T::from(self.data[0])
31    }
32
33    // Return a scalar containing the magnitude.
34    pub fn mag(&self) -> Scalar<f64, D> {
35        Scalar {
36            data: [self.data[0].mag()],
37            _phantom: PhantomData,
38        }
39    }
40}
41
42impl<E: TensorElement, D> Scalar<E, D> {
43    pub fn epsilon(&self) -> Self {
44        Self::EPSILON
45    }
46}
47
48/// A trait to convert a value into a Scalar tensor.
49pub trait ToScalar<E: TensorElement> {
50    fn scalar<U: Unit>(&self) -> Scalar<E, U::Dimension>;
51}
52
53impl<E: TensorElement> ToScalar<E> for E {
54    fn scalar<U: Unit>(&self) -> Scalar<E, U::Dimension> {
55        Scalar {
56            data: [*self],
57            _phantom: PhantomData,
58        }
59    }
60}
61