nautilus_core/ffi/
uuid.rs1use std::{
17 collections::hash_map::DefaultHasher,
18 ffi::{CStr, c_char},
19 hash::{Hash, Hasher},
20};
21
22use crate::UUID4;
23
24#[unsafe(no_mangle)]
25pub extern "C" fn uuid4_new() -> UUID4 {
26 UUID4::new()
27}
28
29#[unsafe(no_mangle)]
39pub unsafe extern "C" fn uuid4_from_cstr(ptr: *const c_char) -> UUID4 {
40 assert!(!ptr.is_null(), "`ptr` was NULL");
41 let cstr = unsafe { CStr::from_ptr(ptr) };
42 let value = cstr.to_str().expect("Failed to convert C string to UTF-8");
43 UUID4::from(value)
44}
45
46#[unsafe(no_mangle)]
47pub extern "C" fn uuid4_to_cstr(uuid: &UUID4) -> *const c_char {
48 uuid.to_cstr().as_ptr()
49}
50
51#[unsafe(no_mangle)]
52pub extern "C" fn uuid4_eq(lhs: &UUID4, rhs: &UUID4) -> u8 {
53 u8::from(lhs == rhs)
54}
55
56#[unsafe(no_mangle)]
57pub extern "C" fn uuid4_hash(uuid: &UUID4) -> u64 {
58 let mut h = DefaultHasher::new();
59 uuid.hash(&mut h);
60 h.finish()
61}
62
63#[cfg(test)]
67mod tests {
68 use std::ffi::CString;
69
70 use rstest::*;
71 use uuid::{self, Uuid};
72
73 use super::*;
74
75 #[rstest]
76 fn test_new() {
77 let uuid = uuid4_new();
78 let uuid_string = uuid.to_string();
79 let uuid_parsed = Uuid::parse_str(&uuid_string).expect("Uuid::parse_str failed");
80 assert_eq!(uuid_parsed.get_version().unwrap(), uuid::Version::Random);
81 }
82
83 #[rstest]
84 fn test_from_cstr() {
85 let uuid_string = "2d89666b-1a1e-4a75-b193-4eb3b454c757";
86 let uuid_cstring = CString::new(uuid_string).expect("CString::new failed");
87 let uuid_ptr = uuid_cstring.as_ptr();
88 let uuid = unsafe { uuid4_from_cstr(uuid_ptr) };
89 assert_eq!(uuid_string, uuid.to_string());
90 }
91
92 #[rstest]
93 fn test_to_cstr() {
94 let uuid_string = "2d89666b-1a1e-4a75-b193-4eb3b454c757";
95 let uuid = UUID4::from(uuid_string);
96 let uuid_ptr = uuid4_to_cstr(&uuid);
97 let uuid_cstr = unsafe { CStr::from_ptr(uuid_ptr) };
98 let uuid_result_string = uuid_cstr.to_str().expect("CStr::to_str failed").to_string();
99 assert_eq!(uuid_string, uuid_result_string);
100 }
101
102 #[rstest]
103 fn test_eq() {
104 let uuid1 = UUID4::from("2d89666b-1a1e-4a75-b193-4eb3b454c757");
105 let uuid2 = UUID4::from("2d89666b-1a1e-4a75-b193-4eb3b454c757");
106 let uuid3 = UUID4::from("2d89666b-1a1e-4a75-b193-4eb3b454c758");
107 assert_eq!(uuid4_eq(&uuid1, &uuid2), 1);
108 assert_eq!(uuid4_eq(&uuid1, &uuid3), 0);
109 }
110
111 #[rstest]
112 fn test_hash() {
113 let uuid1 = UUID4::from("2d89666b-1a1e-4a75-b193-4eb3b454c757");
114 let uuid2 = UUID4::from("2d89666b-1a1e-4a75-b193-4eb3b454c757");
115 let uuid3 = UUID4::from("2d89666b-1a1e-4a75-b193-4eb3b454c758");
116 assert_eq!(uuid4_hash(&uuid1), uuid4_hash(&uuid2));
117 assert_ne!(uuid4_hash(&uuid1), uuid4_hash(&uuid3));
118 }
119}