Struct std::str::Utf8Error1.0.0[][src]

pub struct Utf8Error { /* fields omitted */ }
Expand description

尝试将 u8 的序列解释为字符串时可能发生的错误。

这样,例如 String&strfrom_utf8 系列函数和方法都利用了此错误。

Examples

此错误类型的方法可用于创建类似于 String::from_utf8_lossy 的功能,而无需分配堆内存:

fn from_utf8_lossy<F>(mut input: &[u8], mut push: F) where F: FnMut(&str) {
    loop {
        match std::str::from_utf8(input) {
            Ok(valid) => {
                push(valid);
                break
            }
            Err(error) => {
                let (valid, after_valid) = input.split_at(error.valid_up_to());
                unsafe {
                    push(std::str::from_utf8_unchecked(valid))
                }
                push("\u{FFFD}");

                if let Some(invalid_sequence_length) = error.error_len() {
                    input = &after_valid[invalid_sequence_length..]
                } else {
                    break
                }
            }
        }
    }
}
Run

Implementations

返回给定字符串中的索引,直到对其进行有效 UTF-8 验证为止。

它是使 from_utf8(&input[..index]) 返回 Ok(_) 的最大索引。

Examples

基本用法:

use std::str;

// vector 中的一些无效字节
let sparkle_heart = vec![0, 159, 146, 150];

// std::str::from_utf8 返回 Utf8Error
let error = str::from_utf8(&sparkle_heart).unwrap_err();

// 第二个字节在这里无效
assert_eq!(1, error.valid_up_to());
Run

提供有关失败的更多信息:

  • None: 输入的末尾意外到达。 self.valid_up_to() 从输入末尾开始是 1 到 3 个字节。 如果字节流 (例如文件或网络套接字) 正在以增量方式进行解码,则这可能是有效的 char,其 UTF-8 字节序列跨越了多个块。

  • Some(len): 遇到意外的字节。 提供的长度是从 valid_up_to() 给定的索引处开始的无效字节序列的长度。 如果有损解码,则应在该序列之后 (插入 U+FFFD REPLACEMENT CHARACTER 之后) 恢复解码。

Trait Implementations

返回值的副本。 Read more

source 执行复制分配。 Read more

使用给定的格式化程序格式化该值。 Read more

使用给定的格式化程序格式化该值。 Read more

👎 Deprecated since 1.42.0:

use the Display impl or to_string()

此错误的下级来源 (如果有)。 Read more

🔬 This is a nightly-only experimental API. (backtrace #53487)

返回发生错误的栈回溯 (如果有)。 Read more

👎 Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

此方法测试 selfother 值是否相等,并由 == 使用。 Read more

此方法测试 !=

Auto Trait Implementations

Blanket Implementations

获取 selfTypeIdRead more

从拥有的值中一成不变地借用。 Read more

从拥有的值中借用。 Read more

执行转换。

执行转换。

获得所有权后的结果类型。

通常通过克隆从借用数据中创建拥有的数据。 Read more

🔬 This is a nightly-only experimental API. (toowned_clone_into #41263)

recently added

使用借来的数据来替换拥有的数据,通常是通过克隆。 Read more

将给定值转换为 StringRead more

发生转换错误时返回的类型。

执行转换。

发生转换错误时返回的类型。

执行转换。