Skip to content

Commit 5900dae

Browse files
committedDec 13, 2018
Auto merge of rust-lang#56142 - jnqnfe:osstr_lossy_example, r=alexcrichton
[std] Osstr lossy example

File tree

1 file changed

+33
-8
lines changed

1 file changed

+33
-8
lines changed
 

‎src/libstd/ffi/os_str.rs

+33-8
Original file line numberDiff line numberDiff line change
@@ -536,17 +536,42 @@ impl OsStr {
536536
///
537537
/// # Examples
538538
///
539-
/// Calling `to_string_lossy` on an `OsStr` with valid unicode:
539+
/// Calling `to_string_lossy` on an `OsStr` with invalid unicode:
540540
///
541541
/// ```
542-
/// use std::ffi::OsStr;
543-
///
544-
/// let os_str = OsStr::new("foo");
545-
/// assert_eq!(os_str.to_string_lossy(), "foo");
542+
/// // Note, due to differences in how Unix and Windows represent strings,
543+
/// // we are forced to complicate this example, setting up example `OsStr`s
544+
/// // with different source data and via different platform extensions.
545+
/// // Understand that in reality you could end up with such example invalid
546+
/// // sequences simply through collecting user command line arguments, for
547+
/// // example.
548+
///
549+
/// #[cfg(any(unix, target_os = "redox"))] {
550+
/// use std::ffi::OsStr;
551+
/// use std::os::unix::ffi::OsStrExt;
552+
///
553+
/// // Here, the values 0x66 and 0x6f correspond to 'f' and 'o'
554+
/// // respectively. The value 0x80 is a lone continuation byte, invalid
555+
/// // in a UTF-8 sequence.
556+
/// let source = [0x66, 0x6f, 0x80, 0x6f];
557+
/// let os_str = OsStr::from_bytes(&source[..]);
558+
///
559+
/// assert_eq!(os_str.to_string_lossy(), "fo�o");
560+
/// }
561+
/// #[cfg(windows)] {
562+
/// use std::ffi::OsString;
563+
/// use std::os::windows::prelude::*;
564+
///
565+
/// // Here the values 0x0066 and 0x006f correspond to 'f' and 'o'
566+
/// // respectively. The value 0xD800 is a lone surrogate half, invalid
567+
/// // in a UTF-16 sequence.
568+
/// let source = [0x0066, 0x006f, 0xD800, 0x006f];
569+
/// let os_string = OsString::from_wide(&source[..]);
570+
/// let os_str = os_string.as_os_str();
571+
///
572+
/// assert_eq!(os_str.to_string_lossy(), "fo�o");
573+
/// }
546574
/// ```
547-
///
548-
/// Had `os_str` contained invalid unicode, the `to_string_lossy` call might
549-
/// have returned `"fo�"`.
550575
#[stable(feature = "rust1", since = "1.0.0")]
551576
pub fn to_string_lossy(&self) -> Cow<str> {
552577
self.inner.to_string_lossy()

0 commit comments

Comments
 (0)
Please sign in to comment.