1 //! Defines utf8 error type.
5 /// Errors which can occur when attempting to interpret a sequence of [`u8`]
8 /// As such, the `from_utf8` family of functions and methods for both [`String`]s
9 /// and [`&str`]s make use of this error, for example.
11 /// [`String`]: ../../std/string/struct.String.html#method.from_utf8
12 /// [`&str`]: super::from_utf8
16 /// This error type’s methods can be used to create functionality
17 /// similar to `String::from_utf8_lossy` without allocating heap memory:
20 /// fn from_utf8_lossy<F>(mut input: &[u8], mut push: F) where F: FnMut(&str) {
22 /// match std::str::from_utf8(input) {
28 /// let (valid, after_valid) = input.split_at(error.valid_up_to());
30 /// push(std::str::from_utf8_unchecked(valid))
34 /// if let Some(invalid_sequence_length) = error.error_len() {
35 /// input = &after_valid[invalid_sequence_length..]
44 #[derive(Copy, Eq, PartialEq, Clone, Debug)]
45 #[stable(feature = "rust1", since = "1.0.0")]
46 pub struct Utf8Error {
47 pub(super) valid_up_to: usize,
48 pub(super) error_len: Option<u8>,
52 /// Returns the index in the given string up to which valid UTF-8 was
55 /// It is the maximum index such that `from_utf8(&input[..index])`
56 /// would return `Ok(_)`.
65 /// // some invalid bytes, in a vector
66 /// let sparkle_heart = vec![0, 159, 146, 150];
68 /// // std::str::from_utf8 returns a Utf8Error
69 /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
71 /// // the second byte is invalid here
72 /// assert_eq!(1, error.valid_up_to());
74 #[stable(feature = "utf8_error", since = "1.5.0")]
75 #[rustc_const_unstable(feature = "const_str_from_utf8", issue = "91006")]
78 pub const fn valid_up_to(&self) -> usize {
82 /// Provides more information about the failure:
84 /// * `None`: the end of the input was reached unexpectedly.
85 /// `self.valid_up_to()` is 1 to 3 bytes from the end of the input.
86 /// If a byte stream (such as a file or a network socket) is being decoded incrementally,
87 /// this could be a valid `char` whose UTF-8 byte sequence is spanning multiple chunks.
89 /// * `Some(len)`: an unexpected byte was encountered.
90 /// The length provided is that of the invalid byte sequence
91 /// that starts at the index given by `valid_up_to()`.
92 /// Decoding should resume after that sequence
93 /// (after inserting a [`U+FFFD REPLACEMENT CHARACTER`][U+FFFD]) in case of
96 /// [U+FFFD]: ../../std/char/constant.REPLACEMENT_CHARACTER.html
97 #[stable(feature = "utf8_error_error_len", since = "1.20.0")]
98 #[rustc_const_unstable(feature = "const_str_from_utf8", issue = "91006")]
101 pub const fn error_len(&self) -> Option<usize> {
102 // This should become `map` again, once it's `const`
103 match self.error_len {
104 Some(len) => Some(len as usize),
110 #[stable(feature = "rust1", since = "1.0.0")]
111 impl fmt::Display for Utf8Error {
112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113 if let Some(error_len) = self.error_len {
116 "invalid utf-8 sequence of {} bytes from index {}",
117 error_len, self.valid_up_to
120 write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to)
125 /// An error returned when parsing a `bool` using [`from_str`] fails
127 /// [`from_str`]: super::FromStr::from_str
128 #[derive(Debug, Clone, PartialEq, Eq)]
130 #[stable(feature = "rust1", since = "1.0.0")]
131 pub struct ParseBoolError;
133 #[stable(feature = "rust1", since = "1.0.0")]
134 impl fmt::Display for ParseBoolError {
135 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136 "provided string was not `true` or `false`".fmt(f)