Skip to main content

tensor4all_tensorbackend/
any_scalar.rs

1use std::cmp::Ordering;
2use std::fmt;
3use std::ops::{Add, Div, Mul, Neg, Sub};
4
5use anyhow::{anyhow, ensure, Result};
6use num_complex::{Complex32, Complex64};
7use num_traits::{One, Zero};
8use tenferro::{DType, Tensor as NativeTensor, TensorScalar};
9
10use crate::storage::{Storage, SumFromStorage};
11use crate::tensor_element::TensorElement;
12
13/// Dynamic scalar value shared by every tensor4all scalar wrapper.
14///
15/// This is the single definition of the dynamic scalar value: [`BackendScalar`]
16/// here and `tensor4all_core::AnyScalar` both hold one and delegate their value
17/// accessors ([`real`](Self::real), [`imag`](Self::imag), [`abs`](Self::abs),
18/// [`is_complex`](Self::is_complex), [`is_zero`](Self::is_zero),
19/// [`into_complex`](Self::into_complex)) to it, so the two wrappers cannot
20/// disagree on a value. It is public because the core scalar wrapper lives in a
21/// downstream crate; the wrappers, not this enum, are the user-facing API.
22///
23/// The variants are exactly the scalar payloads this backend can hold: the four
24/// floating types ([`ScalarTensorElement`]) and the three non-floating kinds a
25/// rank-0 native tensor can carry. `tensor4all_core` only ever constructs the
26/// floating variants, because it reads values from `IdxTensor`, whose element
27/// types are [`ScalarTensorElement`].
28#[derive(Clone, Copy, Debug, PartialEq)]
29pub enum ScalarValue {
30    /// 32-bit floating point.
31    F32(f32),
32    /// 64-bit floating point.
33    F64(f64),
34    /// 32-bit signed integer.
35    I32(i32),
36    /// 64-bit signed integer.
37    I64(i64),
38    /// Boolean.
39    Bool(bool),
40    /// 32-bit complex floating point.
41    C32(Complex32),
42    /// 64-bit complex floating point.
43    C64(Complex64),
44}
45
46impl From<f64> for ScalarValue {
47    fn from(value: f64) -> Self {
48        Self::F64(value)
49    }
50}
51
52impl From<f32> for ScalarValue {
53    fn from(value: f32) -> Self {
54        Self::F32(value)
55    }
56}
57
58impl From<Complex64> for ScalarValue {
59    fn from(value: Complex64) -> Self {
60        Self::C64(value)
61    }
62}
63
64impl From<Complex32> for ScalarValue {
65    fn from(value: Complex32) -> Self {
66        Self::C32(value)
67    }
68}
69
70impl ScalarValue {
71    /// Real part as `f64`; `0.0` imaginary means the value equals this.
72    pub fn real(self) -> f64 {
73        match self {
74            Self::F32(value) => value as f64,
75            Self::F64(value) => value,
76            Self::I32(value) => value as f64,
77            Self::I64(value) => value as f64,
78            Self::Bool(value) => {
79                if value {
80                    1.0
81                } else {
82                    0.0
83                }
84            }
85            Self::C32(value) => value.re as f64,
86            Self::C64(value) => value.re,
87        }
88    }
89
90    /// Imaginary part as `f64`; `0.0` for the non-complex variants.
91    pub fn imag(self) -> f64 {
92        match self {
93            Self::F32(_) | Self::F64(_) | Self::I32(_) | Self::I64(_) | Self::Bool(_) => 0.0,
94            Self::C32(value) => value.im as f64,
95            Self::C64(value) => value.im,
96        }
97    }
98
99    /// Magnitude as `f64`.
100    ///
101    /// Integer and boolean kinds widen with `as`/`From` conversions, so an
102    /// integer above 2^53 rounds to the nearest `f64` before the absolute value
103    /// is taken (never negated, so `i32::MIN` and `i64::MIN` stay correct).
104    /// Both complex kinds widen their parts to `f64` first and then use
105    /// `f64::hypot`, so a `c32` magnitude is not rounded through an `f32`
106    /// intermediate. Any NaN part yields `NaN`.
107    pub fn abs(self) -> f64 {
108        match self {
109            Self::F32(value) => value.abs() as f64,
110            Self::F64(value) => value.abs(),
111            Self::I32(value) => f64::from(value).abs(),
112            Self::I64(value) => (value as f64).abs(),
113            Self::Bool(value) => {
114                if value {
115                    1.0
116                } else {
117                    0.0
118                }
119            }
120            // Both complex kinds widen their parts before forming the modulus,
121            // so a `c32` magnitude never rounds through an `f32` intermediate.
122            Self::C32(value) => {
123                if value.re.is_nan() || value.im.is_nan() {
124                    f64::NAN
125                } else {
126                    f64::from(value.re).hypot(f64::from(value.im))
127                }
128            }
129            Self::C64(value) => {
130                if value.re.is_nan() || value.im.is_nan() {
131                    f64::NAN
132                } else {
133                    value.re.hypot(value.im)
134                }
135            }
136        }
137    }
138
139    /// Whether this is one of the complex variants.
140    pub fn is_complex(self) -> bool {
141        matches!(self, Self::C32(_) | Self::C64(_))
142    }
143
144    /// Exact comparison against zero of the variant's own payload type.
145    pub fn is_zero(self) -> bool {
146        match self {
147            Self::F32(value) => value == 0.0,
148            Self::F64(value) => value == 0.0,
149            Self::I32(value) => value == 0,
150            Self::I64(value) => value == 0,
151            Self::Bool(value) => !value,
152            Self::C32(value) => value == Complex32::new(0.0, 0.0),
153            Self::C64(value) => value == Complex64::new(0.0, 0.0),
154        }
155    }
156
157    /// Value widened to `Complex64` with a zero imaginary part when real.
158    pub fn into_complex(self) -> Complex64 {
159        match self {
160            Self::F32(value) => Complex64::new(value as f64, 0.0),
161            Self::F64(value) => Complex64::new(value, 0.0),
162            Self::I32(value) => Complex64::new(value as f64, 0.0),
163            Self::I64(value) => Complex64::new(value as f64, 0.0),
164            Self::Bool(value) => Complex64::new(if value { 1.0 } else { 0.0 }, 0.0),
165            Self::C32(value) => Complex64::new(value.re as f64, value.im as f64),
166            Self::C64(value) => value,
167        }
168    }
169}
170
171/// Snapshot a compact storage reduction as the dynamic scalar kind it was stored as.
172///
173/// The dispatch follows the storage's own dtype instead of assuming `f64` for every real payload: a
174/// narrow `f32` storage yields an `f32` scalar and a `c32` storage a `c32` scalar, exactly as
175/// [`SumFromStorage`] defines them, so a reduction never changes the scalar kind.
176fn scalar_value_from_storage(storage: &Storage) -> ScalarValue {
177    match storage.dtype() {
178        DType::F32 => ScalarValue::F32(f32::sum_from_storage(storage)),
179        DType::F64 => ScalarValue::F64(f64::sum_from_storage(storage)),
180        DType::C32 => ScalarValue::C32(Complex32::sum_from_storage(storage)),
181        DType::C64 => ScalarValue::C64(Complex64::sum_from_storage(storage)),
182        // `Storage` wraps exactly the four floating payloads above, so no other dtype can be stored.
183        other => crate::invariant_violated(
184            "compact storage reduction",
185            format!("compact storage carries no {other:?} payload"),
186        ),
187    }
188}
189
190fn scalar_value_from_native(native: &NativeTensor) -> Result<ScalarValue> {
191    ensure!(
192        native.shape().is_empty(),
193        "expected rank-0 scalar tensor, got shape {:?}",
194        native.shape()
195    );
196
197    match native.dtype() {
198        DType::F32 => native
199            .as_slice::<f32>()
200            .map_err(anyhow::Error::new)?
201            .first()
202            .copied()
203            .map(ScalarValue::F32)
204            .ok_or_else(|| anyhow!("failed to read f32 scalar tensor value")),
205        DType::F64 => native
206            .as_slice::<f64>()
207            .map_err(anyhow::Error::new)?
208            .first()
209            .copied()
210            .map(ScalarValue::F64)
211            .ok_or_else(|| anyhow!("failed to read f64 scalar tensor value")),
212        DType::I32 => native
213            .as_slice::<i32>()
214            .map_err(anyhow::Error::new)?
215            .first()
216            .copied()
217            .map(ScalarValue::I32)
218            .ok_or_else(|| anyhow!("failed to read i32 scalar tensor value")),
219        DType::I64 => native
220            .as_slice::<i64>()
221            .map_err(anyhow::Error::new)?
222            .first()
223            .copied()
224            .map(ScalarValue::I64)
225            .ok_or_else(|| anyhow!("failed to read i64 scalar tensor value")),
226        DType::Bool => native
227            .as_slice::<bool>()
228            .map_err(anyhow::Error::new)?
229            .first()
230            .copied()
231            .map(ScalarValue::Bool)
232            .ok_or_else(|| anyhow!("failed to read bool scalar tensor value")),
233        DType::C32 => native
234            .as_slice::<Complex32>()
235            .map_err(anyhow::Error::new)?
236            .first()
237            .copied()
238            .map(ScalarValue::C32)
239            .ok_or_else(|| anyhow!("failed to read c32 scalar tensor value")),
240        // An external scalar kind is a caller-registered Rust type; it has no
241        // logical scalar value in this crate.
242        DType::External(_) => Err(anyhow::Error::new(tenferro_tensor::Error::unsupported(
243            "scalar snapshot",
244            format!(
245                "external scalar kind {:?} is not a supported scalar tensor",
246                native.dtype()
247            ),
248        ))),
249        DType::C64 => native
250            .as_slice::<Complex64>()
251            .map_err(anyhow::Error::new)?
252            .first()
253            .copied()
254            .map(ScalarValue::C64)
255            .ok_or_else(|| anyhow!("failed to read c64 scalar tensor value")),
256    }
257}
258
259/// Maps a concrete tensor element type onto its [`ScalarValue`] variant.
260///
261/// This is the single implementation of the scalar construction contract:
262/// [`BackendScalar::from_value`] here and `tensor4all_core::AnyScalar::from_value`
263/// use it instead of each matching on the element type. It is public for the
264/// same reason as [`ScalarValue`]: the core wrapper is in a downstream crate and
265/// bounds its own `from_value` on this trait. Implemented for `f32`, `f64`,
266/// [`Complex32`], and [`Complex64`].
267///
268/// # Examples
269///
270/// ```
271/// use num_complex::Complex64;
272/// use tensor4all_tensorbackend::{BackendScalar, ScalarTensorElement, ScalarValue};
273///
274/// assert_eq!(Complex64::scalar_value(Complex64::new(1.0, -2.0)), ScalarValue::C64(Complex64::new(1.0, -2.0)));
275/// assert!((BackendScalar::from_value(Complex64::new(3.0, -4.0)).abs() - 5.0).abs() < 1e-12);
276/// ```
277pub trait ScalarTensorElement: TensorElement {
278    /// Lifts this concrete element into its dynamic scalar variant.
279    fn scalar_value(value: Self) -> ScalarValue;
280}
281
282fn scalar_native<T: TensorScalar>(value: T) -> NativeTensor {
283    NativeTensor::from_vec_col_major(vec![], vec![value]).unwrap_or_else(|error| {
284        crate::invariant_violated("rank-0 scalar construction failed", error)
285    })
286}
287
288impl ScalarTensorElement for f32 {
289    fn scalar_value(value: Self) -> ScalarValue {
290        ScalarValue::F32(value)
291    }
292}
293
294impl ScalarTensorElement for f64 {
295    fn scalar_value(value: Self) -> ScalarValue {
296        ScalarValue::F64(value)
297    }
298}
299
300impl ScalarTensorElement for Complex32 {
301    fn scalar_value(value: Self) -> ScalarValue {
302        ScalarValue::C32(value)
303    }
304}
305
306impl ScalarTensorElement for Complex64 {
307    fn scalar_value(value: Self) -> ScalarValue {
308        ScalarValue::C64(value)
309    }
310}
311
312pub(crate) fn promote_scalar_native(native: &NativeTensor, target: DType) -> Result<NativeTensor> {
313    let promoted = match (scalar_value_from_native(native)?, target) {
314        (ScalarValue::F32(value), DType::F32) => BackendScalar::from_value(value),
315        (ScalarValue::F32(value), DType::F64) => BackendScalar::from_value(value as f64),
316        (ScalarValue::F32(value), DType::C32) => {
317            BackendScalar::from_value(Complex32::new(value, 0.0))
318        }
319        (ScalarValue::F32(value), DType::C64) => {
320            BackendScalar::from_value(Complex64::new(value as f64, 0.0))
321        }
322        (ScalarValue::F32(_), DType::I64) => {
323            return Err(anyhow!(
324                "cannot promote f32 scalar to i64 without truncation"
325            ));
326        }
327        (ScalarValue::F32(_), DType::I32 | DType::Bool) => {
328            return Err(anyhow!(
329                "cannot promote f32 scalar to integer/bool without truncation"
330            ));
331        }
332        (ScalarValue::F64(value), DType::F32) => BackendScalar::from_value(value as f32),
333        (ScalarValue::F64(value), DType::F64) => BackendScalar::from_value(value),
334        (ScalarValue::F64(_), DType::I64) => {
335            return Err(anyhow!(
336                "cannot promote f64 scalar to i64 without truncation"
337            ));
338        }
339        (ScalarValue::F64(_), DType::I32 | DType::Bool) => {
340            return Err(anyhow!(
341                "cannot promote f64 scalar to integer/bool without truncation"
342            ));
343        }
344        (ScalarValue::F64(value), DType::C32) => {
345            BackendScalar::from_value(Complex32::new(value as f32, 0.0))
346        }
347        (ScalarValue::F64(value), DType::C64) => {
348            BackendScalar::from_value(Complex64::new(value, 0.0))
349        }
350        (ScalarValue::I32(value), DType::F32) => BackendScalar::from_value(value as f32),
351        (ScalarValue::I32(value), DType::F64) => BackendScalar::from_value(value as f64),
352        (ScalarValue::I32(value), DType::I32) => return Ok(scalar_native(value)),
353        (ScalarValue::I32(value), DType::I64) => BackendScalar::from_i64(value as i64),
354        (ScalarValue::I32(value), DType::C32) => {
355            BackendScalar::from_value(Complex32::new(value as f32, 0.0))
356        }
357        (ScalarValue::I32(value), DType::C64) => {
358            BackendScalar::from_value(Complex64::new(value as f64, 0.0))
359        }
360        (ScalarValue::I32(_), DType::Bool) => {
361            return Err(anyhow!("cannot promote i32 scalar to bool"));
362        }
363        (ScalarValue::I64(value), DType::F32) => BackendScalar::from_value(value as f32),
364        (ScalarValue::I64(value), DType::F64) => BackendScalar::from_value(value as f64),
365        (ScalarValue::I64(_), DType::I32 | DType::Bool) => {
366            return Err(anyhow!("cannot promote i64 scalar to i32/bool"));
367        }
368        (ScalarValue::I64(value), DType::I64) => BackendScalar::from_i64(value),
369        (ScalarValue::I64(value), DType::C32) => {
370            BackendScalar::from_value(Complex32::new(value as f32, 0.0))
371        }
372        (ScalarValue::I64(value), DType::C64) => {
373            BackendScalar::from_value(Complex64::new(value as f64, 0.0))
374        }
375        (ScalarValue::Bool(value), DType::F32) => {
376            BackendScalar::from_value(if value { 1.0_f32 } else { 0.0_f32 })
377        }
378        (ScalarValue::Bool(value), DType::F64) => {
379            BackendScalar::from_value(if value { 1.0 } else { 0.0 })
380        }
381        (ScalarValue::Bool(value), DType::I32) => {
382            return Ok(scalar_native(if value { 1 } else { 0 }));
383        }
384        (ScalarValue::Bool(value), DType::I64) => {
385            BackendScalar::from_i64(if value { 1 } else { 0 })
386        }
387        (ScalarValue::Bool(value), DType::Bool) => return Ok(scalar_native(value)),
388        (ScalarValue::Bool(value), DType::C32) => {
389            BackendScalar::from_value(Complex32::new(if value { 1.0 } else { 0.0 }, 0.0))
390        }
391        (ScalarValue::Bool(value), DType::C64) => {
392            BackendScalar::from_value(Complex64::new(if value { 1.0 } else { 0.0 }, 0.0))
393        }
394        (ScalarValue::C32(value), DType::F32) => BackendScalar::from_value(value.re),
395        (ScalarValue::C32(value), DType::F64) => BackendScalar::from_value(value.re as f64),
396        (ScalarValue::C32(_), DType::I32 | DType::I64 | DType::Bool) => {
397            return Err(anyhow!("cannot promote c32 scalar to integer/bool"));
398        }
399        (ScalarValue::C32(value), DType::C32) => BackendScalar::from_value(value),
400        (ScalarValue::C32(value), DType::C64) => {
401            BackendScalar::from_value(Complex64::new(value.re as f64, value.im as f64))
402        }
403        (ScalarValue::C64(value), DType::F32) => BackendScalar::from_value(value.re as f32),
404        (ScalarValue::C64(value), DType::F64) => BackendScalar::from_value(value.re),
405        (ScalarValue::C64(_), DType::I32 | DType::I64 | DType::Bool) => {
406            return Err(anyhow!("cannot promote c64 scalar to integer/bool"));
407        }
408        (ScalarValue::C64(value), DType::C32) => {
409            BackendScalar::from_value(Complex32::new(value.re as f32, value.im as f32))
410        }
411        (ScalarValue::C64(value), DType::C64) => BackendScalar::from_value(value),
412
413        (_, DType::External(_)) => {
414            return Err(anyhow::Error::new(tenferro_tensor::Error::unsupported(
415                "promotion",
416                "external scalar kinds are not promotable dtypes",
417            )));
418        }
419    };
420    Ok(promoted.native)
421}
422
423/// Dynamic scalar used across tensor4all backends.
424///
425/// This is a tensor4all-owned rank-0 wrapper over tenferro's dynamic tensor.
426///
427/// # Examples
428///
429/// ```
430/// use tensor4all_tensorbackend::BackendScalar;
431///
432/// // Real scalar
433/// let a = BackendScalar::new_real(3.14);
434/// assert!((a.real() - 3.14).abs() < 1e-10);
435/// assert_eq!(a.imag(), 0.0);
436/// assert!(a.is_real());
437/// assert!(!a.is_complex());
438///
439/// // Complex scalar
440/// let b = BackendScalar::new_complex(1.0, 2.0);
441/// assert!((b.real() - 1.0).abs() < 1e-10);
442/// assert!((b.imag() - 2.0).abs() < 1e-10);
443/// assert!(b.is_complex());
444///
445/// // Arithmetic
446/// let c = BackendScalar::new_real(2.0);
447/// let d = a + c;
448/// assert!((d.real() - 5.14).abs() < 1e-10);
449/// ```
450pub struct BackendScalar {
451    native: NativeTensor,
452    value: ScalarValue,
453}
454
455impl BackendScalar {
456    fn wrap_native(native: NativeTensor) -> Result<Self> {
457        if native.shape().is_empty() {
458            let value = scalar_value_from_native(&native)?;
459            Ok(Self { native, value })
460        } else {
461            Err(anyhow!(
462                "BackendScalar requires a rank-0 tensor, got shape {:?}",
463                native.shape()
464            ))
465        }
466    }
467
468    fn value(&self) -> ScalarValue {
469        self.value
470    }
471
472    fn from_i64(value: i64) -> Self {
473        Self {
474            native: scalar_native(value),
475            value: ScalarValue::I64(value),
476        }
477    }
478
479    fn from_i32(value: i32) -> Self {
480        Self {
481            native: scalar_native(value),
482            value: ScalarValue::I32(value),
483        }
484    }
485
486    fn from_bool(value: bool) -> Self {
487        Self {
488            native: scalar_native(value),
489            value: ScalarValue::Bool(value),
490        }
491    }
492
493    pub(crate) fn from_native(value: NativeTensor) -> Result<Self> {
494        Self::wrap_native(value)
495    }
496
497    pub(crate) fn as_native(&self) -> &NativeTensor {
498        &self.native
499    }
500
501    /// Creates a scalar from any supported public tensor element type.
502    ///
503    /// # Examples
504    ///
505    /// ```
506    /// use tensor4all_tensorbackend::BackendScalar;
507    ///
508    /// let s = BackendScalar::from_value(3.14_f64);
509    /// assert!((s.real() - 3.14).abs() < 1e-10);
510    ///
511    /// use num_complex::Complex64;
512    /// let z = BackendScalar::from_value(Complex64::new(1.0, 2.0));
513    /// assert!(z.is_complex());
514    /// assert!((z.real() - 1.0).abs() < 1e-10);
515    /// assert!((z.imag() - 2.0).abs() < 1e-10);
516    /// ```
517    pub fn from_value<T: ScalarTensorElement>(value: T) -> Self {
518        Self {
519            native: scalar_native(value),
520            value: T::scalar_value(value),
521        }
522    }
523
524    /// Creates a real scalar from an `f64` value.
525    ///
526    /// # Examples
527    ///
528    /// ```
529    /// use tensor4all_tensorbackend::BackendScalar;
530    ///
531    /// let s = BackendScalar::from_real(2.5);
532    /// assert!((s.real() - 2.5).abs() < 1e-10);
533    /// assert!(s.is_real());
534    /// ```
535    pub fn from_real(x: f64) -> Self {
536        Self::from_value(x)
537    }
538
539    /// Creates a complex scalar from real and imaginary parts.
540    ///
541    /// # Examples
542    ///
543    /// ```
544    /// use tensor4all_tensorbackend::BackendScalar;
545    ///
546    /// let s = BackendScalar::from_complex(1.0, -1.0);
547    /// assert!((s.real() - 1.0).abs() < 1e-10);
548    /// assert!((s.imag() - (-1.0)).abs() < 1e-10);
549    /// assert!(s.is_complex());
550    /// ```
551    pub fn from_complex(re: f64, im: f64) -> Self {
552        Self::from_value(Complex64::new(re, im))
553    }
554
555    /// Backward-compatible constructor for a real scalar.
556    ///
557    /// # Examples
558    ///
559    /// ```
560    /// use tensor4all_tensorbackend::BackendScalar;
561    ///
562    /// let s = BackendScalar::new_real(42.0);
563    /// assert!((s.real() - 42.0).abs() < 1e-10);
564    /// ```
565    pub fn new_real(x: f64) -> Self {
566        Self::from_real(x)
567    }
568
569    /// Backward-compatible constructor for a complex scalar.
570    ///
571    /// # Examples
572    ///
573    /// ```
574    /// use tensor4all_tensorbackend::BackendScalar;
575    ///
576    /// let s = BackendScalar::new_complex(3.0, 4.0);
577    /// assert!((s.abs() - 5.0).abs() < 1e-10); // |3 + 4i| = 5
578    /// ```
579    pub fn new_complex(re: f64, im: f64) -> Self {
580        Self::from_complex(re, im)
581    }
582
583    /// Returns the scalar's plain rank-0 tensor value.
584    ///
585    /// # Examples
586    ///
587    /// ```
588    /// use tensor4all_tensorbackend::BackendScalar;
589    ///
590    /// let s = BackendScalar::new_real(5.0);
591    /// let p = s.primal();
592    /// assert!((p.real() - 5.0).abs() < 1e-10);
593    /// ```
594    pub fn primal(&self) -> Self {
595        self.clone()
596    }
597
598    /// Returns the real part while intentionally dropping AD metadata.
599    ///
600    /// # Examples
601    ///
602    /// ```
603    /// use tensor4all_tensorbackend::BackendScalar;
604    ///
605    /// let s = BackendScalar::new_complex(3.0, 4.0);
606    /// assert!((s.real() - 3.0).abs() < 1e-10);
607    /// ```
608    pub fn real(&self) -> f64 {
609        self.value().real()
610    }
611
612    /// Returns the imaginary part while intentionally dropping AD metadata.
613    ///
614    /// Returns `0.0` for real scalars.
615    ///
616    /// # Examples
617    ///
618    /// ```
619    /// use tensor4all_tensorbackend::BackendScalar;
620    ///
621    /// let s = BackendScalar::new_complex(3.0, 4.0);
622    /// assert!((s.imag() - 4.0).abs() < 1e-10);
623    ///
624    /// let r = BackendScalar::new_real(5.0);
625    /// assert_eq!(r.imag(), 0.0);
626    /// ```
627    pub fn imag(&self) -> f64 {
628        self.value().imag()
629    }
630
631    /// Returns the absolute value while intentionally dropping AD metadata.
632    ///
633    /// For complex scalars, returns the complex modulus (`sqrt(re^2 + im^2)`).
634    ///
635    /// # Examples
636    ///
637    /// ```
638    /// use tensor4all_tensorbackend::BackendScalar;
639    ///
640    /// let s = BackendScalar::new_complex(3.0, 4.0);
641    /// assert!((s.abs() - 5.0).abs() < 1e-10);
642    ///
643    /// let r = BackendScalar::new_real(-7.0);
644    /// assert!((r.abs() - 7.0).abs() < 1e-10);
645    /// ```
646    pub fn abs(&self) -> f64 {
647        self.value().abs()
648    }
649
650    /// Returns true when the scalar is complex.
651    ///
652    /// # Examples
653    ///
654    /// ```
655    /// use tensor4all_tensorbackend::BackendScalar;
656    ///
657    /// assert!(BackendScalar::new_complex(1.0, 0.0).is_complex());
658    /// assert!(!BackendScalar::new_real(1.0).is_complex());
659    /// ```
660    pub fn is_complex(&self) -> bool {
661        self.value().is_complex()
662    }
663
664    /// Returns true when the scalar is real.
665    ///
666    /// # Examples
667    ///
668    /// ```
669    /// use tensor4all_tensorbackend::BackendScalar;
670    ///
671    /// assert!(BackendScalar::new_real(1.0).is_real());
672    /// assert!(!BackendScalar::new_complex(1.0, 2.0).is_real());
673    /// ```
674    pub fn is_real(&self) -> bool {
675        !self.is_complex()
676    }
677
678    /// Returns true when the scalar is zero.
679    ///
680    /// # Examples
681    ///
682    /// ```
683    /// use tensor4all_tensorbackend::BackendScalar;
684    ///
685    /// assert!(BackendScalar::new_real(0.0).is_zero());
686    /// assert!(!BackendScalar::new_real(1.0).is_zero());
687    /// ```
688    pub fn is_zero(&self) -> bool {
689        self.value().is_zero()
690    }
691
692    /// Returns the underlying value as `f64` when real.
693    ///
694    /// Returns `None` for complex scalars.
695    ///
696    /// # Examples
697    ///
698    /// ```
699    /// use tensor4all_tensorbackend::BackendScalar;
700    ///
701    /// let r = BackendScalar::new_real(2.5);
702    /// assert_eq!(r.as_f64(), Some(2.5));
703    ///
704    /// let c = BackendScalar::new_complex(1.0, 1.0);
705    /// assert_eq!(c.as_f64(), None);
706    /// ```
707    pub fn as_f64(&self) -> Option<f64> {
708        match self.value() {
709            ScalarValue::F32(value) => Some(value as f64),
710            ScalarValue::F64(value) => Some(value),
711            ScalarValue::I32(value) => Some(value as f64),
712            ScalarValue::I64(value) => Some(value as f64),
713            ScalarValue::Bool(value) => Some(if value { 1.0 } else { 0.0 }),
714            ScalarValue::C32(_) | ScalarValue::C64(_) => None,
715        }
716    }
717
718    /// Returns the underlying value as `Complex64` when complex.
719    ///
720    /// Returns `None` for real scalars.
721    ///
722    /// # Examples
723    ///
724    /// ```
725    /// use tensor4all_tensorbackend::BackendScalar;
726    /// use num_complex::Complex64;
727    ///
728    /// let c = BackendScalar::new_complex(1.0, 2.0);
729    /// assert_eq!(c.as_c64(), Some(Complex64::new(1.0, 2.0)));
730    ///
731    /// let r = BackendScalar::new_real(1.0);
732    /// assert_eq!(r.as_c64(), None);
733    /// ```
734    pub fn as_c64(&self) -> Option<Complex64> {
735        match self.value() {
736            ScalarValue::F32(_)
737            | ScalarValue::F64(_)
738            | ScalarValue::I32(_)
739            | ScalarValue::I64(_)
740            | ScalarValue::Bool(_) => None,
741            ScalarValue::C32(value) => Some(Complex64::new(value.re as f64, value.im as f64)),
742            ScalarValue::C64(value) => Some(value),
743        }
744    }
745
746    /// Returns the complex conjugate.
747    ///
748    /// For real scalars, returns a copy (conjugate of a real number is itself).
749    ///
750    /// # Examples
751    ///
752    /// ```
753    /// use tensor4all_tensorbackend::BackendScalar;
754    ///
755    /// let c = BackendScalar::new_complex(3.0, 4.0);
756    /// let cc = c.conj();
757    /// assert!((cc.real() - 3.0).abs() < 1e-10);
758    /// assert!((cc.imag() - (-4.0)).abs() < 1e-10);
759    ///
760    /// let r = BackendScalar::new_real(5.0);
761    /// assert!((r.conj().real() - 5.0).abs() < 1e-10);
762    /// ```
763    pub fn conj(&self) -> Self {
764        match self.value() {
765            ScalarValue::F32(value) => Self::from_value(value),
766            ScalarValue::F64(value) => Self::from_value(value),
767            ScalarValue::I32(value) => Self::from_i32(value),
768            ScalarValue::I64(value) => Self::from_i64(value),
769            ScalarValue::Bool(value) => Self::from_bool(value),
770            ScalarValue::C32(value) => Self::from_value(value.conj()),
771            ScalarValue::C64(value) => Self::from_value(value.conj()),
772        }
773    }
774
775    /// Returns the real part as a scalar, preserving scalar semantics.
776    ///
777    /// Unlike [`real`](Self::real), this returns an `BackendScalar` rather than raw `f64`.
778    ///
779    /// # Examples
780    ///
781    /// ```
782    /// use tensor4all_tensorbackend::BackendScalar;
783    ///
784    /// let c = BackendScalar::new_complex(3.0, 4.0);
785    /// let re = c.real_part();
786    /// assert!(re.is_real());
787    /// assert!((re.real() - 3.0).abs() < 1e-10);
788    /// ```
789    pub fn real_part(&self) -> Self {
790        Self::from_real(self.real())
791    }
792
793    /// Returns the imaginary part as a scalar, preserving scalar semantics.
794    ///
795    /// Unlike [`imag`](Self::imag), this returns an `BackendScalar` rather than raw `f64`.
796    /// The result is always a real scalar.
797    ///
798    /// # Examples
799    ///
800    /// ```
801    /// use tensor4all_tensorbackend::BackendScalar;
802    ///
803    /// let c = BackendScalar::new_complex(3.0, 4.0);
804    /// let im = c.imag_part();
805    /// assert!(im.is_real());
806    /// assert!((im.real() - 4.0).abs() < 1e-10);
807    /// ```
808    pub fn imag_part(&self) -> Self {
809        Self::from_real(self.imag())
810    }
811
812    /// Compose a complex scalar from real-valued parts.
813    ///
814    /// # Errors
815    ///
816    /// Returns an error when `real` or `imag` is complex rather than a real
817    /// scalar (an invalid input).
818    ///
819    /// # Examples
820    ///
821    /// ```
822    /// use tensor4all_tensorbackend::BackendScalar;
823    ///
824    /// let re = BackendScalar::new_real(3.0);
825    /// let im = BackendScalar::new_real(4.0);
826    /// let c = BackendScalar::compose_complex(re, im).unwrap();
827    /// assert!(c.is_complex());
828    /// assert!((c.real() - 3.0).abs() < 1e-10);
829    /// assert!((c.imag() - 4.0).abs() < 1e-10);
830    /// ```
831    pub fn compose_complex(real: Self, imag: Self) -> Result<Self> {
832        if !real.is_real() || !imag.is_real() {
833            return Err(anyhow!(
834                "compose_complex requires real-valued inputs, got real={:?}, imag={:?}",
835                real.native.dtype(),
836                imag.native.dtype()
837            ));
838        }
839        Ok(Self::from_complex(real.real(), imag.real()))
840    }
841
842    /// Square root, preserving AD metadata.
843    ///
844    /// Automatically promotes to complex if the value is negative.
845    ///
846    /// # Examples
847    ///
848    /// ```
849    /// use tensor4all_tensorbackend::BackendScalar;
850    ///
851    /// let s = BackendScalar::new_real(9.0);
852    /// assert!((s.sqrt().real() - 3.0).abs() < 1e-10);
853    /// ```
854    pub fn sqrt(&self) -> Self {
855        if self.is_complex() || self.real() < 0.0 {
856            let value = self.value().into_complex().sqrt();
857            if value.im == 0.0 {
858                Self::from_real(value.re)
859            } else {
860                Self::from_value(value)
861            }
862        } else {
863            Self::from_real(self.real().sqrt())
864        }
865    }
866
867    /// Real exponent power, preserving AD metadata.
868    ///
869    /// Automatically promotes to complex when the base is negative and the
870    /// exponent is non-integer.
871    ///
872    /// # Examples
873    ///
874    /// ```
875    /// use tensor4all_tensorbackend::BackendScalar;
876    ///
877    /// let s = BackendScalar::new_real(2.0);
878    /// assert!((s.powf(3.0).real() - 8.0).abs() < 1e-10);
879    /// ```
880    pub fn powf(&self, exponent: f64) -> Self {
881        let needs_complex_promotion =
882            self.is_complex() || (self.real() < 0.0 && exponent.fract() != 0.0);
883        if needs_complex_promotion {
884            let value = self.value().into_complex().powf(exponent);
885            if value.im == 0.0 {
886                Self::from_real(value.re)
887            } else {
888                Self::from_value(value)
889            }
890        } else {
891            Self::from_real(self.real().powf(exponent))
892        }
893    }
894
895    /// Integer exponent power, preserving AD metadata.
896    ///
897    /// # Examples
898    ///
899    /// ```
900    /// use tensor4all_tensorbackend::BackendScalar;
901    ///
902    /// let s = BackendScalar::new_real(3.0);
903    /// assert!((s.powi(2).real() - 9.0).abs() < 1e-10);
904    /// ```
905    pub fn powi(&self, exponent: i32) -> Self {
906        self.powf(exponent as f64)
907    }
908}
909
910impl SumFromStorage for BackendScalar {
911    fn sum_from_storage(storage: &Storage) -> Self {
912        Self::from(scalar_value_from_storage(storage))
913    }
914}
915
916impl From<ScalarValue> for BackendScalar {
917    fn from(value: ScalarValue) -> Self {
918        match value {
919            ScalarValue::F32(value) => Self::from_value(value),
920            ScalarValue::F64(value) => Self::from_value(value),
921            ScalarValue::I32(value) => Self::from_i32(value),
922            ScalarValue::I64(value) => Self::from_i64(value),
923            ScalarValue::Bool(value) => Self::from_bool(value),
924            ScalarValue::C32(value) => Self::from_value(value),
925            ScalarValue::C64(value) => Self::from_value(value),
926        }
927    }
928}
929
930impl From<f32> for BackendScalar {
931    fn from(value: f32) -> Self {
932        Self::from_value(value)
933    }
934}
935
936impl From<f64> for BackendScalar {
937    fn from(value: f64) -> Self {
938        Self::from_value(value)
939    }
940}
941
942impl From<Complex32> for BackendScalar {
943    fn from(value: Complex32) -> Self {
944        Self::from_value(value)
945    }
946}
947
948impl From<Complex64> for BackendScalar {
949    fn from(value: Complex64) -> Self {
950        Self::from_value(value)
951    }
952}
953
954impl TryFrom<BackendScalar> for f64 {
955    type Error = &'static str;
956
957    fn try_from(value: BackendScalar) -> std::result::Result<Self, Self::Error> {
958        match value.value() {
959            ScalarValue::F32(real) => Ok(real as f64),
960            ScalarValue::F64(real) => Ok(real),
961            ScalarValue::I32(real) => Ok(real as f64),
962            ScalarValue::I64(real) => Ok(real as f64),
963            ScalarValue::Bool(real) => Ok(if real { 1.0 } else { 0.0 }),
964            ScalarValue::C32(_) | ScalarValue::C64(_) => {
965                Err("cannot convert complex scalar to f64")
966            }
967        }
968    }
969}
970
971impl From<BackendScalar> for Complex64 {
972    fn from(value: BackendScalar) -> Self {
973        value.value().into_complex()
974    }
975}
976
977impl Add for BackendScalar {
978    type Output = Self;
979
980    fn add(self, rhs: Self) -> Self::Output {
981        match (self.value(), rhs.value()) {
982            (ScalarValue::F32(lhs), ScalarValue::F32(rhs)) => Self::from_value(lhs + rhs),
983            (lhs, rhs) if lhs.is_complex() || rhs.is_complex() => {
984                Self::from_value(lhs.into_complex() + rhs.into_complex())
985            }
986            (lhs, rhs) => Self::from_real(lhs.real() + rhs.real()),
987        }
988    }
989}
990
991impl Sub for BackendScalar {
992    type Output = Self;
993
994    fn sub(self, rhs: Self) -> Self::Output {
995        self + (-rhs)
996    }
997}
998
999impl Mul for BackendScalar {
1000    type Output = Self;
1001
1002    fn mul(self, rhs: Self) -> Self::Output {
1003        match (self.value(), rhs.value()) {
1004            (ScalarValue::F32(lhs), ScalarValue::F32(rhs)) => Self::from_value(lhs * rhs),
1005            (lhs, rhs) if lhs.is_complex() || rhs.is_complex() => {
1006                Self::from_value(lhs.into_complex() * rhs.into_complex())
1007            }
1008            (lhs, rhs) => Self::from_real(lhs.real() * rhs.real()),
1009        }
1010    }
1011}
1012
1013impl Div for BackendScalar {
1014    type Output = Self;
1015
1016    fn div(self, rhs: Self) -> Self::Output {
1017        match (self.value(), rhs.value()) {
1018            (ScalarValue::F32(lhs), ScalarValue::F32(rhs)) => Self::from_value(lhs / rhs),
1019            (lhs, rhs) if lhs.is_complex() || rhs.is_complex() => {
1020                Self::from_value(divide_complex(lhs.into_complex(), rhs.into_complex()))
1021            }
1022            (lhs, rhs) => Self::from_real(lhs.real() / rhs.real()),
1023        }
1024    }
1025}
1026
1027fn divide_complex(lhs: Complex64, rhs: Complex64) -> Complex64 {
1028    if ![lhs.re, lhs.im, rhs.re, rhs.im]
1029        .iter()
1030        .all(|x| x.is_finite())
1031        || (rhs.re == 0.0 && rhs.im == 0.0)
1032    {
1033        return lhs / rhs;
1034    }
1035    if rhs.im == 0.0 {
1036        return Complex64::new(lhs.re / rhs.re, lhs.im / rhs.re);
1037    }
1038    if rhs.re == 0.0 {
1039        return Complex64::new(lhs.im / rhs.im, -lhs.re / rhs.im);
1040    }
1041    if [lhs.re, lhs.im, rhs.re, rhs.im]
1042        .iter()
1043        .all(|&x| has_plain_division_exponent(x))
1044    {
1045        return lhs / rhs;
1046    }
1047    // Keep each component's exponent: scaling a whole complex number can erase
1048    // a tiny component whose contribution to the quotient is representable.
1049    let (a, ae) = split_binary(lhs.re);
1050    let (b, be) = split_binary(lhs.im);
1051    let (c, ce) = split_binary(rhs.re);
1052    let (d, de) = split_binary(rhs.im);
1053    let (denominator, exponent) = add_scaled((c * c, 2 * ce), (d * d, 2 * de));
1054    let (real, re) = add_scaled((a * c, ae + ce), (b * d, be + de));
1055    let (imag, im) = add_scaled((b * c, be + ce), (-a * d, ae + de));
1056    Complex64::new(
1057        scale_binary(real / denominator, re - exponent),
1058        scale_binary(imag / denominator, im - exponent),
1059    )
1060}
1061
1062/// Whether `value` is zero or has magnitude in `[2^-500, 2^501)`.
1063///
1064/// When all four components satisfy this, every product in the textbook
1065/// formula and the denominator `c^2 + d^2` lie in `[2^-1000, 2^1003)`, so
1066/// none of them overflows or loses precision to subnormal rounding, and plain
1067/// division is at least as accurate as the exponent-splitting path.
1068fn has_plain_division_exponent(value: f64) -> bool {
1069    const BIAS: u64 = 1023;
1070    let biased = (value.to_bits() >> 52) & 0x7ff;
1071    value == 0.0 || (BIAS - 500..=BIAS + 500).contains(&biased)
1072}
1073
1074fn split_binary(value: f64) -> (f64, i32) {
1075    if value == 0.0 {
1076        return (value, 0);
1077    }
1078    // INVARIANT: divide_complex checked finite inputs; the exponent is in
1079    // [-1074, 1024], so product exponents and their differences fit in i32.
1080    let exponent = value.abs().log2().floor() as i32;
1081    (scale_binary(value, -exponent), exponent)
1082}
1083
1084fn add_scaled((x, xe): (f64, i32), (y, ye): (f64, i32)) -> (f64, i32) {
1085    let exponent = if x == 0.0 {
1086        ye
1087    } else if y == 0.0 {
1088        xe
1089    } else {
1090        xe.max(ye)
1091    };
1092    (
1093        scale_binary(x, xe - exponent) + scale_binary(y, ye - exponent),
1094        exponent,
1095    )
1096}
1097
1098fn scale_binary(mut value: f64, mut exponent: i32) -> f64 {
1099    while exponent != 0 {
1100        let chunk = exponent.clamp(-512, 512);
1101        value *= 2.0_f64.powi(chunk);
1102        exponent -= chunk;
1103    }
1104    value
1105}
1106
1107impl Neg for BackendScalar {
1108    type Output = Self;
1109
1110    fn neg(self) -> Self::Output {
1111        match self.value() {
1112            ScalarValue::F32(value) => Self::from_value(-value),
1113            ScalarValue::F64(value) => Self::from_value(-value),
1114            ScalarValue::I32(value) => Self::from_i32(-value),
1115            ScalarValue::I64(value) => Self::from_i64(-value),
1116            ScalarValue::Bool(value) => Self::from_real(if value { -1.0 } else { 0.0 }),
1117            ScalarValue::C32(value) => Self::from_value(-value),
1118            ScalarValue::C64(value) => Self::from_value(-value),
1119        }
1120    }
1121}
1122
1123impl Mul<BackendScalar> for f64 {
1124    type Output = BackendScalar;
1125
1126    fn mul(self, rhs: BackendScalar) -> Self::Output {
1127        BackendScalar::from_real(self) * rhs
1128    }
1129}
1130
1131impl Mul<BackendScalar> for Complex64 {
1132    type Output = BackendScalar;
1133
1134    fn mul(self, rhs: BackendScalar) -> Self::Output {
1135        BackendScalar::from(self) * rhs
1136    }
1137}
1138
1139impl Div<BackendScalar> for Complex64 {
1140    type Output = BackendScalar;
1141
1142    fn div(self, rhs: BackendScalar) -> Self::Output {
1143        BackendScalar::from(self) / rhs
1144    }
1145}
1146
1147impl Default for BackendScalar {
1148    fn default() -> Self {
1149        Self::zero()
1150    }
1151}
1152
1153impl Zero for BackendScalar {
1154    fn zero() -> Self {
1155        Self::from_real(0.0)
1156    }
1157
1158    fn is_zero(&self) -> bool {
1159        BackendScalar::is_zero(self)
1160    }
1161}
1162
1163impl One for BackendScalar {
1164    fn one() -> Self {
1165        Self::from_real(1.0)
1166    }
1167}
1168
1169impl PartialEq for BackendScalar {
1170    fn eq(&self, other: &Self) -> bool {
1171        self.native.dtype() == other.native.dtype() && self.value() == other.value()
1172    }
1173}
1174
1175impl PartialOrd for BackendScalar {
1176    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1177        match (self.value(), other.value()) {
1178            (ScalarValue::F32(lhs), ScalarValue::F32(rhs)) => lhs.partial_cmp(&rhs),
1179            (ScalarValue::F32(lhs), ScalarValue::F64(rhs)) => (lhs as f64).partial_cmp(&rhs),
1180            (ScalarValue::F32(lhs), ScalarValue::I32(rhs)) => {
1181                (lhs as f64).partial_cmp(&(rhs as f64))
1182            }
1183            (ScalarValue::F32(lhs), ScalarValue::I64(rhs)) => {
1184                (lhs as f64).partial_cmp(&(rhs as f64))
1185            }
1186            (ScalarValue::F32(lhs), ScalarValue::Bool(rhs)) => {
1187                (lhs as f64).partial_cmp(&(if rhs { 1.0 } else { 0.0 }))
1188            }
1189            (ScalarValue::F64(lhs), ScalarValue::F32(rhs)) => lhs.partial_cmp(&(rhs as f64)),
1190            (ScalarValue::F64(lhs), ScalarValue::F64(rhs)) => lhs.partial_cmp(&rhs),
1191            (ScalarValue::F64(lhs), ScalarValue::I32(rhs)) => lhs.partial_cmp(&(rhs as f64)),
1192            (ScalarValue::F64(lhs), ScalarValue::I64(rhs)) => lhs.partial_cmp(&(rhs as f64)),
1193            (ScalarValue::F64(lhs), ScalarValue::Bool(rhs)) => {
1194                lhs.partial_cmp(&(if rhs { 1.0 } else { 0.0 }))
1195            }
1196            (ScalarValue::I32(lhs), ScalarValue::F32(rhs)) => {
1197                (lhs as f64).partial_cmp(&(rhs as f64))
1198            }
1199            (ScalarValue::I32(lhs), ScalarValue::F64(rhs)) => (lhs as f64).partial_cmp(&rhs),
1200            (ScalarValue::I32(lhs), ScalarValue::I32(rhs)) => lhs.partial_cmp(&rhs),
1201            (ScalarValue::I32(lhs), ScalarValue::I64(rhs)) => {
1202                (lhs as f64).partial_cmp(&(rhs as f64))
1203            }
1204            (ScalarValue::I32(lhs), ScalarValue::Bool(rhs)) => {
1205                (lhs as f64).partial_cmp(&(if rhs { 1.0 } else { 0.0 }))
1206            }
1207            (ScalarValue::I64(lhs), ScalarValue::F32(rhs)) => {
1208                (lhs as f64).partial_cmp(&(rhs as f64))
1209            }
1210            (ScalarValue::I64(lhs), ScalarValue::F64(rhs)) => (lhs as f64).partial_cmp(&rhs),
1211            (ScalarValue::I64(lhs), ScalarValue::I32(rhs)) => {
1212                (lhs as f64).partial_cmp(&(rhs as f64))
1213            }
1214            (ScalarValue::I64(lhs), ScalarValue::I64(rhs)) => lhs.partial_cmp(&rhs),
1215            (ScalarValue::I64(lhs), ScalarValue::Bool(rhs)) => {
1216                (lhs as f64).partial_cmp(&(if rhs { 1.0 } else { 0.0 }))
1217            }
1218            (ScalarValue::Bool(lhs), ScalarValue::F32(rhs)) => {
1219                (if lhs { 1.0 } else { 0.0 }).partial_cmp(&(rhs as f64))
1220            }
1221            (ScalarValue::Bool(lhs), ScalarValue::F64(rhs)) => {
1222                (if lhs { 1.0 } else { 0.0 }).partial_cmp(&rhs)
1223            }
1224            (ScalarValue::Bool(lhs), ScalarValue::I32(rhs)) => {
1225                (if lhs { 1.0 } else { 0.0 }).partial_cmp(&(rhs as f64))
1226            }
1227            (ScalarValue::Bool(lhs), ScalarValue::I64(rhs)) => {
1228                (if lhs { 1.0 } else { 0.0 }).partial_cmp(&(rhs as f64))
1229            }
1230            (ScalarValue::Bool(lhs), ScalarValue::Bool(rhs)) => lhs.partial_cmp(&rhs),
1231            _ => None,
1232        }
1233    }
1234}
1235
1236impl fmt::Display for BackendScalar {
1237    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1238        match self.value() {
1239            ScalarValue::F32(value) => value.fmt(f),
1240            ScalarValue::F64(value) => value.fmt(f),
1241            ScalarValue::I32(value) => value.fmt(f),
1242            ScalarValue::I64(value) => value.fmt(f),
1243            ScalarValue::Bool(value) => value.fmt(f),
1244            ScalarValue::C32(value) => value.fmt(f),
1245            ScalarValue::C64(value) => value.fmt(f),
1246        }
1247    }
1248}
1249
1250impl fmt::Debug for BackendScalar {
1251    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1252        f.debug_struct("BackendScalar")
1253            .field("dtype", &self.native.dtype())
1254            .field("value", &self.value())
1255            .finish()
1256    }
1257}
1258
1259impl Clone for BackendScalar {
1260    fn clone(&self) -> Self {
1261        match self.value {
1262            ScalarValue::F32(value) => Self::from_value(value),
1263            ScalarValue::F64(value) => Self::from_value(value),
1264            ScalarValue::I32(value) => Self::from_i32(value),
1265            ScalarValue::I64(value) => Self::from_i64(value),
1266            ScalarValue::Bool(value) => Self::from_bool(value),
1267            ScalarValue::C32(value) => Self::from_value(value),
1268            ScalarValue::C64(value) => Self::from_value(value),
1269        }
1270    }
1271}
1272
1273#[cfg(test)]
1274mod tests;