Utf8Error in std::str - Rust (original) (raw)

Struct Utf8Error

1.0.0 · Source

pub struct Utf8Error { /* private fields */ }

Expand description

Errors which can occur when attempting to interpret a sequence of u8as a string.

As such, the from_utf8 family of functions and methods for both Strings and &strs make use of this error, for example.

§Examples

This error type’s methods can be used to create functionality similar to String::from_utf8_lossy without allocating heap memory:

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
                }
            }
        }
    }
}

Source§

1.5.0 (const: 1.63.0) · Source

Returns the index in the given string up to which valid UTF-8 was verified.

It is the maximum index such that from_utf8(&input[..index])would return Ok(_).

§Examples

Basic usage:

use std::str;

// some invalid bytes, in a vector
let sparkle_heart = vec![0, 159, 146, 150];

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

// the second byte is invalid here
assert_eq!(1, error.valid_up_to());

1.20.0 (const: 1.63.0) · Source

Provides more information about the failure:

1.0.0 · Source§

1.0.0 · Source§

1.0.0 · Source§

1.0.0 · Source§

Source§

👎Deprecated since 1.42.0: use the Display impl or to_string()

1.30.0 · Source§

Returns the lower-level source of this error, if any. Read more

1.0.0 · Source§

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting

Source§

🔬This is a nightly-only experimental API. (error_generic_member_access #99301)

Provides type-based access to context intended for error reports. Read more

1.0.0 · Source§

Source§

Tests for self and other values to be equal, and is used by ==.

1.0.0 · Source§

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

1.0.0 · Source§

1.0.0 · Source§

1.0.0 · Source§

§

§

§

§

§

§