ion_c_sys/
decimal.rs

1// Copyright Amazon.com, Inc. or its affiliates.
2
3//! Provides higher-level APIs for `ION_DECIMAL`
4
5use crate::result::*;
6use crate::*;
7
8use std::ops::{Deref, DerefMut};
9
10/// Smart Pointer over `ION_DECIMAL` to ensure that `ion_decimal_free` is invoked on the instance.
11pub struct IonDecimalPtr {
12    /// Unlike `ION_INT`, we can own the memory of the `ION_DECIMAL` structure itself, but its
13    /// underlying components are managed by `ion_decimal_free`.
14    value: ION_DECIMAL,
15}
16
17impl IonDecimalPtr {
18    /// Creates an `ION_DECIMAL` from an `i32`.
19    pub fn try_from_i32(value: i32) -> IonCResult<Self> {
20        let mut decimal = Self::try_from_existing(ION_DECIMAL::default())?;
21        ionc!(ion_decimal_from_int32(decimal.as_mut_ptr(), value))?;
22        Ok(decimal)
23    }
24
25    /// Creates an `ION_DECIMAL` from a `BigDecimal`.
26    pub fn try_from_bigdecimal(value: &BigDecimal) -> IonCResult<Self> {
27        let mut decimal = Self::try_from_existing(ION_DECIMAL::default())?;
28        decimal.try_assign_bigdecimal(value)?;
29        Ok(decimal)
30    }
31
32    /// Creates and `ION_DECIMAL` from a `decQuad`.
33    pub fn try_from_decquad(value: decQuad) -> IonCResult<Self> {
34        let ion_decimal = ION_DECIMAL {
35            type_: ION_DECIMAL_TYPE_ION_DECIMAL_TYPE_QUAD,
36            value: _ion_decimal__bindgen_ty_1 { quad_value: value },
37        };
38
39        Self::try_from_existing(ion_decimal)
40    }
41
42    /// Binds an existing `ION_DECIMAL` to a pointer.
43    pub fn try_from_existing(value: ION_DECIMAL) -> IonCResult<Self> {
44        Ok(Self { value })
45    }
46
47    /// Returns the underlying `ION_DECIMAL` as a mutable pointer.
48    pub fn as_mut_ptr(&mut self) -> *mut ION_DECIMAL {
49        &mut self.value
50    }
51}
52
53impl Deref for IonDecimalPtr {
54    type Target = ION_DECIMAL;
55
56    fn deref(&self) -> &Self::Target {
57        &self.value
58    }
59}
60
61impl DerefMut for IonDecimalPtr {
62    fn deref_mut(&mut self) -> &mut Self::Target {
63        &mut self.value
64    }
65}
66
67impl Drop for IonDecimalPtr {
68    fn drop(&mut self) {
69        unsafe {
70            ion_decimal_free(&mut self.value);
71        }
72    }
73}