Skip to main content

core/str/
error.rs

1//! Defines utf8 error type.
2
3use crate::error::Error;
4use crate::fmt;
5
6/// Errors which can occur when attempting to interpret a sequence of [`u8`]
7/// as a string.
8///
9/// As such, the `from_utf8` family of functions and methods for both [`String`]s
10/// and [`&str`]s make use of this error, for example.
11///
12/// [`String`]: ../../std/string/struct.String.html#method.from_utf8
13/// [`&str`]: super::from_utf8
14///
15/// # Examples
16///
17/// This error type’s methods can be used to create functionality
18/// similar to `String::from_utf8_lossy` without allocating heap memory:
19///
20/// ```
21/// fn from_utf8_lossy<F>(mut input: &[u8], mut push: F) where F: FnMut(&str) {
22///     loop {
23///         match std::str::from_utf8(input) {
24///             Ok(valid) => {
25///                 push(valid);
26///                 break
27///             }
28///             Err(error) => {
29///                 let (valid, after_valid) = input.split_at(error.valid_up_to());
30///                 unsafe {
31///                     push(std::str::from_utf8_unchecked(valid))
32///                 }
33///                 push("\u{FFFD}");
34///
35///                 if let Some(invalid_sequence_length) = error.error_len() {
36///                     input = &after_valid[invalid_sequence_length..]
37///                 } else {
38///                     break
39///                 }
40///             }
41///         }
42///     }
43/// }
44/// ```
45#[derive(Copy, Eq, PartialEq, Clone, Debug)]
46#[stable(feature = "rust1", since = "1.0.0")]
47#[ferrocene::prevalidated]
48pub struct Utf8Error {
49    pub(super) valid_up_to: usize,
50    pub(super) error_len: Option<u8>,
51}
52
53impl Utf8Error {
54    /// Returns the index in the given string up to which valid UTF-8 was
55    /// verified.
56    ///
57    /// It is the maximum index such that `from_utf8(&input[..index])`
58    /// would return `Ok(_)`.
59    ///
60    /// # Examples
61    ///
62    /// Basic usage:
63    ///
64    /// ```
65    /// use std::str;
66    ///
67    /// // some invalid bytes, in a vector
68    /// let sparkle_heart = vec![0, 159, 146, 150];
69    ///
70    /// // std::str::from_utf8 returns a Utf8Error
71    /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
72    ///
73    /// // the second byte is invalid here
74    /// assert_eq!(1, error.valid_up_to());
75    /// ```
76    #[stable(feature = "utf8_error", since = "1.5.0")]
77    #[rustc_const_stable(feature = "const_str_from_utf8_shared", since = "1.63.0")]
78    #[must_use]
79    #[inline]
80    #[ferrocene::prevalidated]
81    pub const fn valid_up_to(&self) -> usize {
82        self.valid_up_to
83    }
84
85    /// Provides more information about the failure:
86    ///
87    /// * `None`: the end of the input was reached unexpectedly.
88    ///   `self.valid_up_to()` is 1 to 3 bytes from the end of the input.
89    ///   If a byte stream (such as a file or a network socket) is being decoded incrementally,
90    ///   this could be a valid `char` whose UTF-8 byte sequence is spanning multiple chunks.
91    ///
92    /// * `Some(len)`: an unexpected byte was encountered.
93    ///   The length provided is that of the invalid byte sequence
94    ///   that starts at the index given by `valid_up_to()`.
95    ///   Decoding should resume after that sequence
96    ///   (after inserting a [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD]) in case of
97    ///   lossy decoding.
98    ///
99    /// [U+FFFD]: ../../std/char/constant.REPLACEMENT_CHARACTER.html
100    #[stable(feature = "utf8_error_error_len", since = "1.20.0")]
101    #[rustc_const_stable(feature = "const_str_from_utf8_shared", since = "1.63.0")]
102    #[must_use]
103    #[inline]
104    #[ferrocene::prevalidated]
105    pub const fn error_len(&self) -> Option<usize> {
106        // FIXME(const-hack): This should become `map` again, once it's `const`
107        match self.error_len {
108            Some(len) => Some(len as usize),
109            None => None,
110        }
111    }
112}
113
114#[stable(feature = "rust1", since = "1.0.0")]
115impl fmt::Display for Utf8Error {
116    #[ferrocene::prevalidated]
117    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118        if let Some(error_len) = self.error_len {
119            write!(
120                f,
121                "invalid utf-8 sequence of {} bytes from index {}",
122                error_len, self.valid_up_to
123            )
124        } else {
125            write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to)
126        }
127    }
128}
129
130#[stable(feature = "rust1", since = "1.0.0")]
131impl Error for Utf8Error {}
132
133/// An error returned when parsing a `bool` using [`from_str`] fails
134///
135/// [`from_str`]: super::FromStr::from_str
136#[derive(Debug, Clone, PartialEq, Eq)]
137#[non_exhaustive]
138#[stable(feature = "rust1", since = "1.0.0")]
139pub struct ParseBoolError;
140
141#[stable(feature = "rust1", since = "1.0.0")]
142impl fmt::Display for ParseBoolError {
143    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144        "provided string was not `true` or `false`".fmt(f)
145    }
146}
147
148#[stable(feature = "rust1", since = "1.0.0")]
149impl Error for ParseBoolError {}