Skip to main content

decimal_scaled/
convert_trait.rs

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