plist_plus/types/
integer.rs

1// jkcoxson
2
3use log::trace;
4
5use crate::{error::PlistError, unsafe_bindings, Plist, PlistType};
6
7impl Plist {
8    /// Creates a new plist with the type of an integer
9    pub fn new_uint(uint: u64) -> Plist {
10        trace!("Generating new uint plist");
11        unsafe { unsafe_bindings::plist_new_uint(uint) }.into()
12    }
13    /// Sets the plist as type integer with the given value
14    pub fn set_uint_val(&self, val: u64) {
15        trace!("Setting uint value");
16        unsafe { unsafe_bindings::plist_set_uint_val(self.plist_t, val) }
17    }
18    /// Returns the value of the integer
19    pub fn get_uint_val(&self) -> Result<u64, PlistError> {
20        if self.plist_type != PlistType::Integer {
21            return Err(PlistError::InvalidArg);
22        }
23        let mut val = unsafe { std::mem::zeroed() };
24        trace!("Getting uint value");
25        Ok(unsafe {
26            unsafe_bindings::plist_get_uint_val(self.plist_t, &mut val);
27            val
28        })
29    }
30}
31
32impl TryFrom<Plist> for u64 {
33    type Error = PlistError;
34    fn try_from(plist: Plist) -> Result<Self, Self::Error> {
35        plist.get_uint_val()
36    }
37}
38
39impl From<u64> for Plist {
40    fn from(val: u64) -> Self {
41        Plist::new_uint(val)
42    }
43}
44
45impl TryFrom<Plist> for u32 {
46    type Error = PlistError;
47    fn try_from(plist: Plist) -> Result<Self, Self::Error> {
48        plist.get_uint_val().map(|val| val as u32)
49    }
50}
51
52impl From<u32> for Plist {
53    fn from(val: u32) -> Self {
54        Plist::new_uint(val as u64)
55    }
56}
57
58impl TryFrom<Plist> for u16 {
59    type Error = PlistError;
60    fn try_from(plist: Plist) -> Result<Self, Self::Error> {
61        plist.get_uint_val().map(|val| val as u16)
62    }
63}
64
65impl From<u16> for Plist {
66    fn from(val: u16) -> Self {
67        Plist::new_uint(val as u64)
68    }
69}
70
71impl TryFrom<Plist> for u8 {
72    type Error = PlistError;
73    fn try_from(plist: Plist) -> Result<Self, Self::Error> {
74        plist.get_uint_val().map(|val| val as u8)
75    }
76}
77
78impl From<u8> for Plist {
79    fn from(val: u8) -> Self {
80        Plist::new_uint(val as u64)
81    }
82}
83
84impl TryFrom<Plist> for usize {
85    type Error = PlistError;
86    fn try_from(plist: Plist) -> Result<Self, Self::Error> {
87        plist.get_uint_val().map(|x| x as usize)
88    }
89}
90
91impl From<usize> for Plist {
92    fn from(val: usize) -> Self {
93        Plist::new_uint(val as u64)
94    }
95}
96
97#[cfg(test)]
98mod tests {
99    use super::*;
100
101    #[test]
102    fn int_test() {
103        let p = Plist::new_uint(123412340987);
104        p.set_uint_val(098709781234);
105        assert_eq!(p.get_uint_val().unwrap(), 098709781234);
106    }
107}