Skip to main content

decimal_scaled/types/traits/
convert.rs

1// SPDX-FileCopyrightText: 2026 John Moxley
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! The [`DecimalConvert`] trait — round-trip + integer conversion +
5//! float bridge shared by every decimal width.
6//!
7//! Split out of the original [`crate::Decimal`] trait alongside
8//! [`crate::DecimalArithmetic`], [`crate::DecimalTranscendental`],
9//! and [`crate::DecimalConstants`]; `Decimal` is now a marker
10//! supertrait that requires all four. Callers who only need
11//! conversions (not the operator surface or transcendentals) can
12//! target this narrower bound; supertraits [`DecimalArithmetic`] so
13//! `Self::Storage` and `Self::ZERO` / `Self::MAX` / `Self::MIN`
14//! (needed for saturation paths) are in scope.
15//!
16//! See [`crate::types::traits::decimal`] for the full scope rationale.
17
18use crate::support::rounding::RoundingMode;
19use crate::types::traits::arithmetic::DecimalArithmetic;
20
21/// Round-trip + conversion surface shared by every decimal width.
22///
23/// Supertraits [`DecimalArithmetic`] so the storage type and
24/// boundary constants are accessible for saturation logic.
25pub trait DecimalConvert: DecimalArithmetic {
26    // ── Round-trip ───────────────────────────────────────────────────
27
28    /// Constructs from a raw storage value.
29    fn from_bits(raw: Self::Storage) -> Self;
30
31    /// Returns the raw storage value.
32    fn to_bits(self) -> Self::Storage;
33
34    /// Returns the decimal scale of this value.
35    fn scale(self) -> u32;
36
37    // ── Integer conversion ───────────────────────────────────────────
38    //
39    // Construction from a primitive integer is the fallible
40    // `TryFrom<iN>` surface on each concrete width (overflow on scaling
41    // returns `ConvertError::Overflow`); there is no width-generic
42    // integer constructor on this trait. Only the to-integer direction
43    // lives here.
44
45    /// Convert to `i64` using the crate-default rounding mode.
46    fn to_int(self) -> i64;
47
48    /// Convert to `i64` using the supplied rounding mode.
49    fn to_int_with(self, mode: RoundingMode) -> i64;
50
51    // ── Float bridge (lossy) ─────────────────────────────────────────
52
53    /// Construct from `f64` using the crate-default rounding mode.
54    #[cfg(feature = "std")]
55    fn from_f64(value: f64) -> Self;
56
57    /// Construct from `f64` using the supplied rounding mode.
58    #[cfg(feature = "std")]
59    fn from_f64_with(value: f64, mode: RoundingMode) -> Self;
60
61    /// Convert to `f64`. Lossy when the storage magnitude exceeds
62    /// `f64`'s ~15-digit exact range.
63    #[cfg(feature = "std")]
64    fn to_f64(self) -> f64;
65
66    /// Convert to `f32`. Lossy.
67    #[cfg(feature = "std")]
68    fn to_f32(self) -> f32;
69}