-
Notifications
You must be signed in to change notification settings - Fork 51
/
Copy pathstring.rs
341 lines (311 loc) · 11.6 KB
/
string.rs
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
#![cfg(feature = "CFBase")]
use core::cmp::Ordering;
use core::ffi::{c_char, CStr};
use core::fmt::Write;
use core::ptr::NonNull;
use core::{fmt, str};
use crate::{
kCFAllocatorNull, CFRange, CFRetained, CFString, CFStringBuiltInEncodings, CFStringCompare,
CFStringCompareFlags, CFStringCreateWithBytes, CFStringCreateWithBytesNoCopy, CFStringGetBytes,
CFStringGetCStringPtr, CFStringGetLength,
};
#[track_caller]
unsafe fn debug_checked_utf8_unchecked(bytes: &[u8]) -> &str {
if cfg!(debug_assertions) {
match str::from_utf8(bytes) {
Ok(s) => s,
Err(err) => panic!(
"unsafe precondition violated: CF function did not return valid UTF-8: {err}"
),
}
} else {
// SAFETY: Checked by caller
unsafe { str::from_utf8_unchecked(bytes) }
}
}
impl CFString {
/// Creates a new `CFString` from a [`str`][prim@str].
#[doc(alias = "CFStringCreateWithBytes")]
#[allow(clippy::should_implement_trait)] // Not really sure of a better name
pub fn from_str(string: &str) -> CFRetained<CFString> {
let len = string.len().try_into().expect("string too large");
let s = unsafe {
CFStringCreateWithBytes(
None,
string.as_ptr(),
len,
CFStringBuiltInEncodings::EncodingUTF8.0,
false,
)
};
// Should only fail if the string is not UTF-u (which we know it is)
// or perhaps on allocation error.
s.expect("failed creating CFString")
}
/// Creates a new `CFString` from a `'static` [`str`][prim@str].
///
/// This may be slightly more efficient than [`CFString::from_str`], as it
/// may be able to re-use the existing buffer (since we know it won't be
/// deallocated).
#[doc(alias = "CFStringCreateWithBytesNoCopy")]
pub fn from_static_str(string: &'static str) -> CFRetained<CFString> {
let len = string.len().try_into().expect("string too large");
// SAFETY: The string is used as a backing store, and thus must
// potentially live forever, since we don't know how long the returned
// CFString will be alive for. This is ensured by the `'static`
// requirement.
let s = unsafe {
CFStringCreateWithBytesNoCopy(
None,
string.as_ptr(),
len,
CFStringBuiltInEncodings::EncodingUTF8.0,
false,
kCFAllocatorNull,
)
};
s.expect("failed creating CFString")
}
/// Get the [`str`](`prim@str`) representation of this string if it can be
/// done efficiently.
///
/// Returns [`None`] if the internal storage does not allow this to be
/// done efficiently. Use `CFString::to_string` if performance is not an
/// issue.
///
///
/// # Safety
///
/// The `CFString` must not be mutated for the lifetime of the returned
/// string.
///
/// Warning: This is very difficult to ensure in generic contexts, e.g. it
/// cannot even be used inside `Debug::fmt`, since `Formatter` uses `dyn`
/// internally, and can thus mutate the string inside there.
#[doc(alias = "CFStringGetCStringPtr")]
// NOTE: This is NOT public, since it's completely broken for differently
// encoded strings, see the `as_str_broken` test below.
#[allow(dead_code)]
unsafe fn as_str_unchecked(&self) -> Option<&str> {
let bytes =
unsafe { CFStringGetCStringPtr(self, CFStringBuiltInEncodings::EncodingUTF8.0) };
NonNull::new(bytes as *mut c_char).map(|bytes| {
// SAFETY: The pointer is valid for as long as the CFString is not
// mutated (which the caller ensures it isn't for the lifetime of
// the reference).
//
// We won't accidentally truncate the string here, since
// `CFStringGetCStringPtr` makes sure that there are no internal
// NUL bytes in the string.
//
// TODO: Verify this claim with a test.
let cstr = unsafe { CStr::from_ptr(bytes.as_ptr()) };
// SAFETY: `CFStringGetCStringPtr` is (very likely) implemented
// correctly, and won't return non-UTF8 strings.
unsafe { debug_checked_utf8_unchecked(cstr.to_bytes()) }
})
}
}
impl fmt::Display for CFString {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Copy UTF-8 bytes from the CFString to the formatter in a loop, to
// avoid allocating.
//
// We have to do this instead of using `CFStringGetCStringPtr`, as
// that will be invalidated if the string is mutated while in use, and
// `fmt::Formatter` contains `dyn Write` which may very theoretically
// do exactly that.
// Somewhat reasonably sized stack buffer.
// TODO: Do performance testing, and tweak this value.
//
// Should be at least 4 (as that's the minimum size of `char`).
let mut buf = [0u8; 32];
let mut location_utf16 = 0;
loop {
let len_utf16 = unsafe { CFStringGetLength(self) };
let mut read_utf8 = 0;
let read_utf16 = unsafe {
CFStringGetBytes(
self,
CFRange {
location: location_utf16,
length: len_utf16 - location_utf16,
},
CFStringBuiltInEncodings::EncodingUTF8.0,
0, // No conversion character
false,
buf.as_mut_ptr(),
buf.len() as _,
&mut read_utf8,
)
};
if read_utf16 <= 0 {
if location_utf16 < len_utf16 {
// We're not done reading the entire string yet; emit
// replacement character, advance one character, and try again.
f.write_char(char::REPLACEMENT_CHARACTER)?;
location_utf16 += 1;
continue;
}
break;
}
location_utf16 += read_utf16;
// SAFETY: `CFStringGetBytes` is (very likely) implemented
// correctly, and won't return non-UTF8 strings.
//
// Even if a string contains an UTF-8 char on a boundary, it won't
// split it up when returning UTF-8.
let s = unsafe { debug_checked_utf8_unchecked(&buf[0..read_utf8 as usize]) };
// NOTE: May unwind, and may invalidate the string contents.
f.write_str(s)?;
}
Ok(())
}
}
impl PartialOrd for CFString {
#[inline]
#[doc(alias = "CFStringCompare")]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for CFString {
#[inline]
#[doc(alias = "CFStringCompare")]
fn cmp(&self, other: &Self) -> Ordering {
// Request standard lexiographical ordering.
let flags = CFStringCompareFlags::empty();
unsafe { CFStringCompare(self, Some(other), flags) }.into()
}
}
#[cfg(test)]
mod tests {
use alloc::string::ToString;
use super::*;
use crate::{CFStringCreateWithCString, CFStringGetCString};
#[test]
fn basic_conversion() {
let s = CFString::from_str("abc");
assert_eq!(s.to_string(), "abc");
let s = CFString::from_str("a♥😀");
assert_eq!(s.to_string(), "a♥😀");
}
#[test]
fn cstr_conversion() {
let table = [
(
b"abc\xf8xyz\0" as &[u8],
CFStringBuiltInEncodings::EncodingISOLatin1,
"abcøxyz",
),
(
b"\x26\x65\0",
CFStringBuiltInEncodings::EncodingUTF16BE,
"♥",
),
(
b"\x65\x26\0",
CFStringBuiltInEncodings::EncodingUTF16LE,
"♥",
),
];
for (cstr, encoding, expected) in table {
let cstr = CStr::from_bytes_with_nul(cstr).unwrap();
let s = unsafe { CFStringCreateWithCString(None, cstr.as_ptr(), encoding.0) }.unwrap();
assert_eq!(s.to_string(), expected);
}
}
#[test]
fn from_incomplete() {
let s = unsafe {
CFStringCreateWithBytes(
None,
b"\xd8\x3d\xde".as_ptr(),
3,
CFStringBuiltInEncodings::EncodingUTF16BE.0,
false,
)
.unwrap()
};
assert_eq!(s.to_string(), "�"); // Replacement character
assert_eq!(unsafe { CFStringGetLength(&s) }, 1);
}
#[test]
fn internal_nul_byte() {
let s = CFString::from_str("a\0b\0c\0d");
// Works with `CFStringGetBytes`.
assert_eq!(s.to_string(), "a\0b\0c\0d");
// Test `CFStringGetCString`.
let mut buf = [0u8; 10];
assert!(unsafe {
CFStringGetCString(
&s,
buf.as_mut_ptr().cast(),
buf.len() as _,
CFStringBuiltInEncodings::EncodingUTF8.0,
)
});
// All the data is copied to the buffer.
assert_eq!(&buf[0..10], b"a\0b\0c\0d\0\0\0");
// But subsequent usage of that as a CStr fails, since it contains
// interior NUL bytes.
let cstr = CStr::from_bytes_until_nul(&buf).unwrap();
assert_eq!(cstr.to_bytes(), b"a");
}
#[test]
fn utf8_on_boundary() {
// Make the emoji lie across the 32 byte buffer size in Display::fmt.
let s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa😀"; // 29 'a's
assert_eq!(CFString::from_str(s).to_string(), s);
let s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa😀"; // 30 'a's
assert_eq!(CFString::from_str(s).to_string(), s);
let s = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa😀"; // 31 'a's
assert_eq!(CFString::from_str(s).to_string(), s);
}
#[test]
fn as_str_broken() {
// A CFString that is supposed to contain a "♥" (the UTF-8 encoding of
// that is the vastly different b"\xE2\x99\xA5").
let s = unsafe {
CFStringCreateWithCString(
None,
b"\x65\x26\0".as_ptr().cast(),
CFStringBuiltInEncodings::EncodingUnicode.0,
)
}
.unwrap();
// `CFStringGetBytes` used in `fmt::Display` converts to UTF-8.
assert_eq!(s.to_string(), "♥");
// So does `CFStringGetCString`.
let mut buf = [0u8; 20];
assert!(unsafe {
CFStringGetCString(
&s,
buf.as_mut_ptr().cast(),
buf.len() as _,
CFStringBuiltInEncodings::EncodingUTF8.0,
)
});
let cstr = CStr::from_bytes_until_nul(&buf).unwrap();
assert_eq!(cstr.to_bytes(), "♥".as_bytes());
// But `CFStringGetCStringPtr` completely ignores the UTF-8 conversion
// we asked it to do, i.e. a huge correctness footgun!
assert_eq!(unsafe { s.as_str_unchecked() }, Some("e&"));
}
#[test]
fn test_static() {
let cf = CFString::from_static_str("xyz");
assert_eq!(cf.to_string(), "xyz");
}
#[test]
fn eq() {
assert_eq!(CFString::from_str("abc"), CFString::from_str("abc"));
assert_ne!(CFString::from_str("abc"), CFString::from_str("xyz"));
// Cross-type comparison
assert_ne!(
**CFString::from_str("abc"),
**unsafe { kCFAllocatorNull }.unwrap()
);
}
// TODO: Test mutation while formatting.
}