Debian Codegraph @

src/apple.rs

raw symbols SCIP
1 use alloc::{string::String, vec::Vec};
2 use core::ffi::c_void;
3
4 type CFIndex = isize;
5 type Boolean = u8;
6 type CFStringEncoding = u32;
7
8 #[allow(non_upper_case_globals)]
9 const kCFStringEncodingUTF8: CFStringEncoding = 0x08000100;
10
11 #[repr(C)]
12 #[derive(Clone, Copy)]
13 struct CFRange {
14 pub location: CFIndex,
15 pub length: CFIndex,
16 }
17
18 type CFTypeRef = *const c_void;
19
20 #[repr(C)]
21 struct __CFArray(c_void);
22 type CFArrayRef = *const __CFArray;
23
24 #[repr(C)]
25 struct __CFString(c_void);
26 type CFStringRef = *const __CFString;
27
28 // Most of these definitions come from `core-foundation-sys`, but we want this crate
29 // to be `no_std` and `core-foundation-sys` isn't currently.
30 #[link(name = "CoreFoundation", kind = "framework")]
31 extern "C" {
32 fn CFArrayGetCount(theArray: CFArrayRef) -> CFIndex;
33 fn CFArrayGetValueAtIndex(theArray: CFArrayRef, idx: CFIndex) -> *const c_void;
34
35 fn CFStringGetLength(theString: CFStringRef) -> CFIndex;
36 fn CFStringGetBytes(
37 theString: CFStringRef,
38 range: CFRange,
39 encoding: CFStringEncoding,
40 lossByte: u8,
41 isExternalRepresentation: Boolean,
42 buffer: *mut u8,
43 maxBufLen: CFIndex,
44 usedBufLen: *mut CFIndex,
45 ) -> CFIndex;
46
47 fn CFRelease(cf: CFTypeRef);
48
49 fn CFLocaleCopyPreferredLanguages() -> CFArrayRef;
50 }
51
52 pub(crate) fn get() -> impl Iterator<Item = String> {
53 let preferred_langs = get_languages();
54 let mut idx = 0;
55
56 #[allow(clippy::as_conversions)]
57 core::iter::from_fn(move || unsafe {
58 let (langs, num_langs) = preferred_langs.as_ref()?;
59
60 // 0 to N-1 inclusive
61 if idx >= *num_langs {
62 return None;
63 }
64
65 // SAFETY: The current index has been checked that its still within bounds of the array.
66 // XXX: We don't retain the strings because we know we have total ownership of the backing array.
67 let locale = CFArrayGetValueAtIndex(langs.0, idx) as CFStringRef;
68 idx += 1;
69
70 // SAFETY: `locale` is a valid CFString pointer because the array will always contain a value.
71 let str_len = CFStringGetLength(locale);
72
73 let range = CFRange {
74 location: 0,
75 length: str_len,
76 };
77
78 let mut capacity = 0;
79 // SAFETY:
80 // - `locale` is a valid CFString
81 // - The supplied range is within the length of the string.
82 // - `capacity` is writable.
83 // Passing NULL and `0` is correct for the buffer to get the
84 // encoded output length.
85 CFStringGetBytes(
86 locale,
87 range,
88 kCFStringEncodingUTF8,
89 0,
90 false as Boolean,
91 core::ptr::null_mut(),
92 0,
93 &mut capacity,
94 );
95
96 // Guard against a zero-sized allocation, if that were to somehow occur.
97 if capacity == 0 {
98 return None;
99 }
100
101 // Note: This is the number of bytes (u8) that will be written to
102 // the buffer, not the number of codepoints they would contain.
103 let mut buffer = Vec::with_capacity(capacity as usize);
104
105 // SAFETY:
106 // - `locale` is a valid CFString
107 // - The supplied range is within the length of the string.
108 // - `buffer` is writable and has sufficent capacity to receive the data.
109 // - `maxBufLen` is correctly based on `buffer`'s available capacity.
110 // - `out_len` is writable.
111 let mut out_len = 0;
112 CFStringGetBytes(
113 locale,
114 range,
115 kCFStringEncodingUTF8,
116 0,
117 false as Boolean,
118 buffer.as_mut_ptr(),
119 capacity as CFIndex,
120 &mut out_len,
121 );
122
123 // Sanity check that both calls to `CFStringGetBytes`
124 // were equivalent. If they weren't, the system is doing
125 // something very wrong...
126 assert!(out_len <= capacity);
127
128 // SAFETY: The system has written `out_len` elements, so they are
129 // initialized and inside the buffer's capacity bounds.
130 buffer.set_len(out_len as usize);
131
132 // This should always contain UTF-8 since we told the system to
133 // write UTF-8 into the buffer, but the value is small enough that
134 // using `from_utf8_unchecked` isn't worthwhile.
135 String::from_utf8(buffer).ok()
136 })
137 }
138
139 fn get_languages() -> Option<(CFArray, CFIndex)> {
140 unsafe {
141 // SAFETY: This function is safe to call and has no invariants. Any value inside the
142 // array will be owned by us.
143 let langs = CFLocaleCopyPreferredLanguages();
144 if !langs.is_null() {
145 let langs = CFArray(langs);
146 // SAFETY: The returned array is a valid CFArray object.
147 let count = CFArrayGetCount(langs.0);
148 if count != 0 {
149 Some((langs, count))
150 } else {
151 None
152 }
153 } else {
154 None
155 }
156 }
157 }
158
159 struct CFArray(CFArrayRef);
160
161 impl Drop for CFArray {
162 fn drop(&mut self) {
163 // SAFETY: This wrapper contains a valid CFArray.
164 unsafe { CFRelease(self.0.cast()) }
165 }
166 }