nautilus_core/ffi/
uuid.rs1use std::{
23 collections::hash_map::DefaultHasher,
24 ffi::{CStr, c_char},
25 hash::{Hash, Hasher},
26};
27
28use crate::{UUID4, ffi::abort_on_panic};
29
30#[unsafe(no_mangle)]
32pub extern "C" fn uuid4_new() -> UUID4 {
33 abort_on_panic(UUID4::new)
34}
35
36#[unsafe(no_mangle)]
46pub unsafe extern "C" fn uuid4_from_cstr(ptr: *const c_char) -> UUID4 {
47 abort_on_panic(|| {
48 assert!(!ptr.is_null(), "`ptr` was NULL");
49 let cstr = unsafe { CStr::from_ptr(ptr) };
50 let value = cstr.to_str().expect("Failed to convert C string to UTF-8");
51 UUID4::from(value)
52 })
53}
54
55#[unsafe(no_mangle)]
60pub extern "C" fn uuid4_to_cstr(uuid: &UUID4) -> *const c_char {
61 abort_on_panic(|| uuid.to_cstr().as_ptr())
62}
63
64#[unsafe(no_mangle)]
66pub extern "C" fn uuid4_eq(lhs: &UUID4, rhs: &UUID4) -> u8 {
67 abort_on_panic(|| u8::from(lhs == rhs))
68}
69
70#[unsafe(no_mangle)]
72pub extern "C" fn uuid4_hash(uuid: &UUID4) -> u64 {
73 abort_on_panic(|| {
74 let mut h = DefaultHasher::new();
75 uuid.hash(&mut h);
76 h.finish()
77 })
78}
79
80#[cfg(test)]
84mod tests {
85 use std::ffi::CString;
86
87 use rstest::*;
88 use uuid::{self, Uuid};
89
90 use super::*;
91
92 #[rstest]
93 fn test_new() {
94 let uuid = uuid4_new();
95 let uuid_string = uuid.to_string();
96 let uuid_parsed = Uuid::parse_str(&uuid_string).expect("Uuid::parse_str failed");
97 assert_eq!(uuid_parsed.get_version().unwrap(), uuid::Version::Random);
98 }
99
100 #[rstest]
101 fn test_from_cstr() {
102 let uuid_string = "2d89666b-1a1e-4a75-b193-4eb3b454c757";
103 let uuid_cstring = CString::new(uuid_string).expect("CString::new failed");
104 let uuid_ptr = uuid_cstring.as_ptr();
105 let uuid = unsafe { uuid4_from_cstr(uuid_ptr) };
106 assert_eq!(uuid_string, uuid.to_string());
107 }
108
109 #[rstest]
110 fn test_to_cstr() {
111 let uuid_string = "2d89666b-1a1e-4a75-b193-4eb3b454c757";
112 let uuid = UUID4::from(uuid_string);
113 let uuid_ptr = uuid4_to_cstr(&uuid);
114 let uuid_cstr = unsafe { CStr::from_ptr(uuid_ptr) };
115 let uuid_result_string = uuid_cstr.to_str().expect("CStr::to_str failed").to_string();
116 assert_eq!(uuid_string, uuid_result_string);
117 }
118
119 #[rstest]
120 fn test_eq() {
121 let uuid1 = UUID4::from("2d89666b-1a1e-4a75-b193-4eb3b454c757");
122 let uuid2 = UUID4::from("2d89666b-1a1e-4a75-b193-4eb3b454c757");
123 let uuid3 = UUID4::from("2d89666b-1a1e-4a75-b193-4eb3b454c758");
124 assert_eq!(uuid4_eq(&uuid1, &uuid2), 1);
125 assert_eq!(uuid4_eq(&uuid1, &uuid3), 0);
126 }
127
128 #[rstest]
129 fn test_hash() {
130 let uuid1 = UUID4::from("2d89666b-1a1e-4a75-b193-4eb3b454c757");
131 let uuid2 = UUID4::from("2d89666b-1a1e-4a75-b193-4eb3b454c757");
132 let uuid3 = UUID4::from("2d89666b-1a1e-4a75-b193-4eb3b454c758");
133 assert_eq!(uuid4_hash(&uuid1), uuid4_hash(&uuid2));
134 assert_ne!(uuid4_hash(&uuid1), uuid4_hash(&uuid3));
135 }
136}