Skip to main content

xur_std/
decimal.rs

1//! `std::decimal` — arbitrary-precision decimal numbers backed by `rust_decimal`.
2
3use facet::Facet;
4use rust_decimal::Decimal;
5use xur_runtime::{Registry, XurStr};
6
7/// Wrapper so we can derive Facet and register as a native type.
8#[derive(Clone, Copy, Facet)]
9#[facet(opaque)]
10pub struct XurDecimal(pub Decimal);
11
12/// A recoverable error from a `std::decimal` operation. Scripts can match the
13/// variant, e.g. `Err(decimal::Error::Parse(msg))`.
14#[derive(Clone, Copy, Facet)]
15#[repr(C)]
16pub enum Error {
17    /// The value does not fit the requested numeric type, or a float cannot be
18    /// represented as a decimal.
19    OutOfRange,
20    /// The string is not a valid decimal number.
21    Parse,
22}
23
24impl std::fmt::Display for Error {
25    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
26        f.write_str(match self {
27            Error::OutOfRange => "value out of range for the target type",
28            Error::Parse => "invalid decimal string",
29        })
30    }
31}
32
33impl std::fmt::Display for XurDecimal {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        write!(f, "{}", self.0)
36    }
37}
38
39impl XurDecimal {
40    /// Pack into the .NET `System.Decimal` memory layout as two u64 register
41    /// values (System V AMD64 ABI).
42    ///
43    /// .NET layout: `[flags:u32, hi:u32, lo:u32, mid:u32]`
44    /// Register 1 (rdi/rsi): `flags | hi << 32`
45    /// Register 2 (rsi/rdx): `lo | mid << 32`
46    pub fn to_dotnet_regs(&self) -> [u64; 2] {
47        let bytes = self.0.serialize();
48        // serialize() = [flags(4), lo(4), mid(4), hi(4)]
49        let flags = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
50        let lo = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
51        let mid = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]);
52        let hi = u32::from_le_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]);
53        // .NET memory order: [flags, hi, lo, mid]
54        let reg0 = (flags as u64) | ((hi as u64) << 32);
55        let reg1 = (lo as u64) | ((mid as u64) << 32);
56        [reg0, reg1]
57    }
58
59    /// Unpack from two u64 register values in the .NET `System.Decimal` ABI layout.
60    pub fn from_dotnet_regs(regs: [u64; 2]) -> Self {
61        let flags = regs[0] as u32;
62        let hi = (regs[0] >> 32) as u32;
63        let lo = regs[1] as u32;
64        let mid = (regs[1] >> 32) as u32;
65        // serialize() format = [flags, lo, mid, hi]
66        let mut bytes = [0u8; 16];
67        bytes[0..4].copy_from_slice(&flags.to_le_bytes());
68        bytes[4..8].copy_from_slice(&lo.to_le_bytes());
69        bytes[8..12].copy_from_slice(&mid.to_le_bytes());
70        bytes[12..16].copy_from_slice(&hi.to_le_bytes());
71        XurDecimal(Decimal::deserialize(bytes))
72    }
73}
74
75pub(crate) fn register(registry: &Registry) {
76    let mut m = registry.module("std::decimal");
77
78    m.ty::<Error>("Error");
79
80    m.ty::<XurDecimal>("Decimal")
81        .method("scale", |d: &XurDecimal| -> i64 { d.0.scale() as i64 })
82        .method("is_sign_negative", |d: &XurDecimal| -> bool {
83            d.0.is_sign_negative()
84        })
85        .method("is_sign_positive", |d: &XurDecimal| -> bool {
86            d.0.is_sign_positive()
87        })
88        .method("abs", |d: &XurDecimal| -> XurDecimal {
89            XurDecimal(d.0.abs())
90        })
91        .method("floor", |d: &XurDecimal| -> XurDecimal {
92            XurDecimal(d.0.floor())
93        })
94        .method("ceil", |d: &XurDecimal| -> XurDecimal {
95            XurDecimal(d.0.ceil())
96        })
97        .method("round", |d: &XurDecimal| -> XurDecimal {
98            XurDecimal(d.0.round())
99        })
100        .method("round_dp", |d: &XurDecimal, dp: i64| -> XurDecimal {
101            XurDecimal(d.0.round_dp(dp as u32))
102        })
103        .method("to_int", |d: &XurDecimal| -> Result<i64, Error> {
104            use rust_decimal::prelude::ToPrimitive;
105            d.0.to_i64().ok_or(Error::OutOfRange)
106        })
107        .method("to_float", |d: &XurDecimal| -> Result<f64, Error> {
108            use rust_decimal::prelude::ToPrimitive;
109            d.0.to_f64().ok_or(Error::OutOfRange)
110        });
111
112    m.named_function("from_int", &["value"], |value: i64| -> XurDecimal {
113        XurDecimal(Decimal::from(value))
114    });
115    m.named_function(
116        "from_float",
117        &["value"],
118        |value: f64| -> Result<XurDecimal, Error> {
119            Decimal::try_from(value)
120                .map(XurDecimal)
121                .map_err(|_| Error::OutOfRange)
122        },
123    );
124    m.named_function(
125        "from_str",
126        &["value"],
127        |value: XurStr| -> Result<XurDecimal, Error> {
128            value
129                .parse::<Decimal>()
130                .map(XurDecimal)
131                .map_err(|_| Error::Parse)
132        },
133    );
134}