1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
use crate::get_api;
use crate::sys;
use std::cmp::Ordering;
use std::cmp::{Eq, PartialEq};
use std::mem::transmute;

/// The RID type is used to access the unique integer ID of a resource.
/// They are opaque, so they do not grant access to the associated resource by themselves.
#[derive(Copy, Clone, Debug)]
pub struct Rid(pub(crate) sys::godot_rid);

impl Rid {
    pub fn new() -> Self {
        Rid::default()
    }

    pub fn get_id(&self) -> i32 {
        unsafe { (get_api().godot_rid_get_id)(&self.0) }
    }

    pub fn operator_less(&self, b: &Rid) -> bool {
        unsafe { (get_api().godot_rid_operator_less)(&self.0, &b.0) }
    }

    pub fn is_valid(&self) -> bool {
        self.to_u64() != 0
    }

    fn to_u64(&self) -> u64 {
        unsafe {
            // std::mem::transmute needs source and destination types to have the same size. On 32
            // bit systems sizeof(void *) != size_of<u64>() so this fails to compile. The bindings
            // define godot_rid as (a newtype of) [u8; u8size] or [u8; u4size] depending on
            // architecture word size so transmuting to usize should always work.
            transmute::<_, usize>(self.0) as _
        }
    }

    #[doc(hidden)]
    pub fn sys(&self) -> *const sys::godot_rid {
        &self.0
    }

    #[doc(hidden)]
    pub fn mut_sys(&mut self) -> *mut sys::godot_rid {
        &mut self.0
    }

    #[doc(hidden)]
    pub fn from_sys(sys: sys::godot_rid) -> Self {
        Rid(sys)
    }
}

impl_basic_traits! {
    for Rid as godot_rid {
        Eq => godot_rid_operator_equal;
        Default => godot_rid_new;
    }
}

impl PartialOrd for Rid {
    fn partial_cmp(&self, other: &Rid) -> Option<Ordering> {
        unsafe {
            let native = (get_api().godot_rid_operator_less)(&self.0, &other.0);

            if native {
                Some(Ordering::Less)
            } else {
                Some(Ordering::Greater)
            }
        }
    }
}