本文简要介绍rust语言中 std::ffi::OsStr.to_string_lossy
的用法。
用法
pub fn to_string_lossy(&self) -> Cow<'_, str>
任何非 Unicode 序列都将替换为 U+FFFD REPLACEMENT CHARACTER
。
例子
使用无效的 unicode 在 OsStr
上调用 to_string_lossy
:
// Note, due to differences in how Unix and Windows represent strings,
// we are forced to complicate this example, setting up example `OsStr`s
// with different source data and via different platform extensions.
// Understand that in reality you could end up with such example invalid
// sequences simply through collecting user command line arguments, for
// example.
#[cfg(unix)] {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
// Here, the values 0x66 and 0x6f correspond to 'f' and 'o'
// respectively. The value 0x80 is a lone continuation byte, invalid
// in a UTF-8 sequence.
let source = [0x66, 0x6f, 0x80, 0x6f];
let os_str = OsStr::from_bytes(&source[..]);
assert_eq!(os_str.to_string_lossy(), "fo�o");
}
#[cfg(windows)] {
use std::ffi::OsString;
use std::os::windows::prelude::*;
// Here the values 0x0066 and 0x006f correspond to 'f' and 'o'
// respectively. The value 0xD800 is a lone surrogate half, invalid
// in a UTF-16 sequence.
let source = [0x0066, 0x006f, 0xD800, 0x006f];
let os_string = OsString::from_wide(&source[..]);
let os_str = os_string.as_os_str();
assert_eq!(os_str.to_string_lossy(), "fo�o");
}
相关用法
- Rust OsStr.to_str用法及代码示例
- Rust OsStr.to_ascii_uppercase用法及代码示例
- Rust OsStr.to_os_string用法及代码示例
- Rust OsStr.to_ascii_lowercase用法及代码示例
- Rust OsStr.make_ascii_lowercase用法及代码示例
- Rust OsStr.len用法及代码示例
- Rust OsStr.eq_ignore_ascii_case用法及代码示例
- Rust OsStr.is_ascii用法及代码示例
- Rust OsStr.is_empty用法及代码示例
- Rust OsStr.make_ascii_uppercase用法及代码示例
- Rust OsStr.new用法及代码示例
- Rust OsString.clear用法及代码示例
- Rust OsString.into_string用法及代码示例
- Rust OsString.new用法及代码示例
- Rust OsString.into_boxed_os_str用法及代码示例
- Rust OsString.reserve_exact用法及代码示例
- Rust OsString.shrink_to_fit用法及代码示例
- Rust OsString.shrink_to用法及代码示例
- Rust OsStringExt用法及代码示例
- Rust OsStringExt.from_wide用法及代码示例
- Rust OsString.push用法及代码示例
- Rust OsString.capacity用法及代码示例
- Rust OsString.reserve用法及代码示例
- Rust OsString.with_capacity用法及代码示例
- Rust OsStrExt用法及代码示例
注:本文由纯净天空筛选整理自rust-lang.org大神的英文原创作品 std::ffi::OsStr.to_string_lossy。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。