ion_c_sys/
int.rs

1// Copyright Amazon.com, Inc. or its affiliates.
2
3//! Provides higher-level APIs for `ION_INT`
4
5use crate::result::*;
6use crate::*;
7
8use std::ops::{Deref, DerefMut};
9use std::ptr;
10
11/// Smart Pointer over `ION_INT` to ensure that `ion_int_free` is invoked on the instance.
12#[derive(Debug)]
13pub struct IonIntPtr {
14    value: *mut ION_INT,
15}
16
17impl IonIntPtr {
18    /// Allocates a new `ION_INT` to zero.
19    pub fn try_new() -> IonCResult<Self> {
20        let mut value = ptr::null_mut();
21        ionc!(ion_int_alloc(ptr::null_mut(), &mut value))?;
22        ionc!(ion_int_init(
23            value,
24            ptr::null_mut(), // no owner - defers to normal Ion C xalloc/xfree
25        ))?;
26
27        Ok(Self { value })
28    }
29
30    /// Allocates a new `ION_INT` from a `BigInt`.
31    pub fn try_from_bigint(value: &BigInt) -> IonCResult<Self> {
32        let mut ion_int = IonIntPtr::try_new()?;
33        ion_int.try_assign_bigint(value)?;
34
35        Ok(ion_int)
36    }
37
38    /// Returns the underlying `ION_INT` as a mutable pointer.
39    pub fn as_mut_ptr(&mut self) -> *mut ION_INT {
40        self.value
41    }
42}
43
44impl Deref for IonIntPtr {
45    type Target = ION_INT;
46
47    fn deref(&self) -> &Self::Target {
48        unsafe { &*(self.value) }
49    }
50}
51
52impl DerefMut for IonIntPtr {
53    fn deref_mut(&mut self) -> &mut Self::Target {
54        unsafe { &mut *(self.value) }
55    }
56}
57
58impl Drop for IonIntPtr {
59    fn drop(&mut self) {
60        unsafe {
61            ion_int_free(self.value);
62        }
63    }
64}