Skip to content

Commit 261ef65

Browse files
committed
Add fast path for displaying pre-validated Wtf8Buf
1 parent 2710bd2 commit 261ef65

File tree

2 files changed

+25
-2
lines changed

2 files changed

+25
-2
lines changed

library/std/src/sys/os_str/wtf8.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,13 @@ impl AsInner<Wtf8> for Buf {
3636

3737
impl fmt::Debug for Buf {
3838
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
39-
fmt::Debug::fmt(self.as_slice(), formatter)
39+
fmt::Debug::fmt(&self.inner, formatter)
4040
}
4141
}
4242

4343
impl fmt::Display for Buf {
4444
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
45-
fmt::Display::fmt(self.as_slice(), formatter)
45+
fmt::Display::fmt(&self.inner, formatter)
4646
}
4747
}
4848

library/std/src/sys_common/wtf8.rs

+23
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,17 @@ impl fmt::Debug for Wtf8Buf {
169169
}
170170
}
171171

172+
/// Formats the string with unpaired surrogates substituted with the replacement
173+
/// character, U+FFFD.
174+
impl fmt::Display for Wtf8Buf {
175+
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
176+
if let Some(s) = self.as_known_utf8() {
177+
return fmt::Display::fmt(s, formatter);
178+
}
179+
fmt::Display::fmt(&**self, formatter)
180+
}
181+
}
182+
172183
impl Wtf8Buf {
173184
/// Creates a new, empty WTF-8 string.
174185
#[inline]
@@ -262,6 +273,18 @@ impl Wtf8Buf {
262273
unsafe { Wtf8::from_mut_bytes_unchecked(&mut self.bytes) }
263274
}
264275

276+
/// Converts the string to UTF-8 without validation, if it was created from
277+
/// valid UTF-8.
278+
#[inline]
279+
fn as_known_utf8(&self) -> Option<&str> {
280+
if self.is_known_utf8 {
281+
// SAFETY: The buffer is known to be valid UTF-8.
282+
Some(unsafe { str::from_utf8_unchecked(self.as_bytes()) })
283+
} else {
284+
None
285+
}
286+
}
287+
265288
/// Reserves capacity for at least `additional` more bytes to be inserted
266289
/// in the given `Wtf8Buf`.
267290
/// The collection may reserve more space to avoid frequent reallocations.

0 commit comments

Comments
 (0)