Debian Codegraph @

third_party/rust/coreaudio-sys-utils/src/string.rs

raw
1 use core_foundation_sys::base::{
2 kCFAllocatorDefault, kCFAllocatorNull, Boolean, CFIndex, CFRange, CFRelease,
3 };
4 use core_foundation_sys::string::{
5 kCFStringEncodingUTF8, CFStringCreateWithBytes, CFStringCreateWithBytesNoCopy,
6 CFStringGetBytes, CFStringGetLength, CFStringRef,
7 };
8 use std::ffi::CString;
9
10 pub fn cfstringref_from_static_string(string: &'static str) -> coreaudio_sys::CFStringRef {
11 // Set deallocator to kCFAllocatorNull to prevent the the memory of the parameter `string`
12 // from being released by CFRelease. We manage the string memory by ourselves.
13 let cfstringref = unsafe {
14 CFStringCreateWithBytesNoCopy(
15 kCFAllocatorDefault,
16 string.as_ptr(),
17 string.len() as CFIndex,
18 kCFStringEncodingUTF8,
19 false as Boolean,
20 kCFAllocatorNull,
21 )
22 };
23 cfstringref as coreaudio_sys::CFStringRef
24 }
25
26 pub fn cfstringref_from_string(string: &str) -> coreaudio_sys::CFStringRef {
27 let cfstringref = unsafe {
28 CFStringCreateWithBytes(
29 kCFAllocatorDefault,
30 string.as_ptr(),
31 string.len() as CFIndex,
32 kCFStringEncodingUTF8,
33 false as Boolean,
34 )
35 };
36 cfstringref as coreaudio_sys::CFStringRef
37 }
38
39 #[derive(Debug)]
40 pub struct StringRef(CFStringRef);
41 impl StringRef {
42 pub fn new(string_ref: CFStringRef) -> Self {
43 assert!(!string_ref.is_null());
44 Self(string_ref)
45 }
46
47 pub fn into_string(self) -> String {
48 self.to_string()
49 }
50
51 pub fn to_cstring(&self) -> CString {
52 unsafe {
53 // Assume that bytes doesn't contain `0` in the middle.
54 CString::from_vec_unchecked(utf8_from_cfstringref(self.0))
55 }
56 }
57
58 pub fn into_cstring(self) -> CString {
59 self.to_cstring()
60 }
61
62 pub fn get_raw(&self) -> CFStringRef {
63 self.0
64 }
65 }
66
67 impl Drop for StringRef {
68 fn drop(&mut self) {
69 use std::os::raw::c_void;
70 unsafe { CFRelease(self.0 as *mut c_void) };
71 }
72 }
73
74 impl std::fmt::Display for StringRef {
75 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76 let string =
77 String::from_utf8(utf8_from_cfstringref(self.0)).expect("convert bytes to a String");
78 write!(f, "{}", string)
79 }
80 }
81
82 fn utf8_from_cfstringref(string_ref: CFStringRef) -> Vec<u8> {
83 use std::ptr;
84
85 assert!(!string_ref.is_null());
86
87 let length: CFIndex = unsafe { CFStringGetLength(string_ref) };
88 if length == 0 {
89 return Vec::new();
90 }
91
92 // Get the buffer size of the string.
93 let range: CFRange = CFRange {
94 location: 0,
95 length,
96 };
97 let mut size: CFIndex = 0;
98 let mut converted_chars: CFIndex = unsafe {
99 CFStringGetBytes(
100 string_ref,
101 range,
102 kCFStringEncodingUTF8,
103 0,
104 false as Boolean,
105 ptr::null_mut() as *mut u8,
106 0,
107 &mut size,
108 )
109 };
110 assert!(converted_chars > 0 && size > 0);
111
112 // Then, allocate the buffer with the required size and actually copy data into it.
113 let mut buffer = vec![b'\x00'; size as usize];
114 converted_chars = unsafe {
115 CFStringGetBytes(
116 string_ref,
117 range,
118 kCFStringEncodingUTF8,
119 0,
120 false as Boolean,
121 buffer.as_mut_ptr(),
122 size,
123 ptr::null_mut() as *mut CFIndex,
124 )
125 };
126 assert!(converted_chars > 0);
127
128 buffer
129 }
130
131 #[cfg(test)]
132 mod test {
133 use super::*;
134
135 #[test]
136 fn test_create_static_cfstring_ref() {
137 const STATIC_STRING: &str = "static string for testing";
138 let stringref =
139 StringRef::new(cfstringref_from_static_string(STATIC_STRING) as CFStringRef);
140 assert_eq!(STATIC_STRING, stringref.to_string());
141 assert_eq!(
142 CString::new(STATIC_STRING).unwrap(),
143 stringref.into_cstring()
144 );
145 // TODO: Find a way to check the string's inner pointer is same.
146 }
147
148 #[test]
149 fn test_create_static_empty_cfstring_ref() {
150 const STATIC_EMPTY_STRING: &str = "";
151 let stringref =
152 StringRef::new(cfstringref_from_static_string(STATIC_EMPTY_STRING) as CFStringRef);
153 assert_eq!(STATIC_EMPTY_STRING, stringref.to_string());
154 assert_eq!(
155 CString::new(STATIC_EMPTY_STRING).unwrap(),
156 stringref.into_cstring()
157 );
158 // TODO: Find a way to check the string's inner pointer is same.
159 }
160
161 #[test]
162 fn test_create_cfstring_ref() {
163 let expected = "Rustaceans 🦀";
164 let stringref = StringRef::new(cfstringref_from_string(expected) as CFStringRef);
165 assert_eq!(expected, stringref.to_string());
166 assert_eq!(CString::new(expected).unwrap(), stringref.into_cstring());
167 // TODO: Find a way to check the string's inner pointer is different.
168 }
169
170 #[test]
171 fn test_create_empty_cfstring_ref() {
172 let expected = "";
173 let stringref = StringRef::new(cfstringref_from_string(expected) as CFStringRef);
174 assert_eq!(expected, stringref.to_string());
175 assert_eq!(CString::new(expected).unwrap(), stringref.into_cstring());
176 // TODO: Find a way to check the string's inner pointer is different.
177 }
178 }