Skip to content

Commit 1de1739

Browse files
committed
Add fast path for displaying pre-validated Wtf8Buf
1 parent 5bc6231 commit 1de1739

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
@@ -166,6 +166,17 @@ impl fmt::Debug for Wtf8Buf {
166166
}
167167
}
168168

169+
/// Formats the string with unpaired surrogates substituted with the replacement
170+
/// character, U+FFFD.
171+
impl fmt::Display for Wtf8Buf {
172+
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
173+
if let Some(s) = self.as_known_utf8() {
174+
return fmt::Display::fmt(s, formatter);
175+
}
176+
fmt::Display::fmt(&**self, formatter)
177+
}
178+
}
179+
169180
impl Wtf8Buf {
170181
/// Creates a new, empty WTF-8 string.
171182
#[inline]
@@ -258,6 +269,18 @@ impl Wtf8Buf {
258269
unsafe { Wtf8::from_mut_bytes_unchecked(&mut self.bytes) }
259270
}
260271

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

0 commit comments

Comments
 (0)