]> git.lizzy.rs Git - rust.git/blob - library/core/src/str/error.rs
Temporarily make `CStr` not a link in the `c_char` docs
[rust.git] / library / core / src / str / error.rs
1 //! Defines utf8 error type.
2
3 use crate::fmt;
4
5 /// Errors which can occur when attempting to interpret a sequence of [`u8`]
6 /// as a string.
7 ///
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.
10 ///
11 /// [`String`]: ../../std/string/struct.String.html#method.from_utf8
12 /// [`&str`]: super::from_utf8
13 ///
14 /// # Examples
15 ///
16 /// This error type’s methods can be used to create functionality
17 /// similar to `String::from_utf8_lossy` without allocating heap memory:
18 ///
19 /// ```
20 /// fn from_utf8_lossy<F>(mut input: &[u8], mut push: F) where F: FnMut(&str) {
21 ///     loop {
22 ///         match std::str::from_utf8(input) {
23 ///             Ok(valid) => {
24 ///                 push(valid);
25 ///                 break
26 ///             }
27 ///             Err(error) => {
28 ///                 let (valid, after_valid) = input.split_at(error.valid_up_to());
29 ///                 unsafe {
30 ///                     push(std::str::from_utf8_unchecked(valid))
31 ///                 }
32 ///                 push("\u{FFFD}");
33 ///
34 ///                 if let Some(invalid_sequence_length) = error.error_len() {
35 ///                     input = &after_valid[invalid_sequence_length..]
36 ///                 } else {
37 ///                     break
38 ///                 }
39 ///             }
40 ///         }
41 ///     }
42 /// }
43 /// ```
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>,
49 }
50
51 impl Utf8Error {
52     /// Returns the index in the given string up to which valid UTF-8 was
53     /// verified.
54     ///
55     /// It is the maximum index such that `from_utf8(&input[..index])`
56     /// would return `Ok(_)`.
57     ///
58     /// # Examples
59     ///
60     /// Basic usage:
61     ///
62     /// ```
63     /// use std::str;
64     ///
65     /// // some invalid bytes, in a vector
66     /// let sparkle_heart = vec![0, 159, 146, 150];
67     ///
68     /// // std::str::from_utf8 returns a Utf8Error
69     /// let error = str::from_utf8(&sparkle_heart).unwrap_err();
70     ///
71     /// // the second byte is invalid here
72     /// assert_eq!(1, error.valid_up_to());
73     /// ```
74     #[stable(feature = "utf8_error", since = "1.5.0")]
75     #[rustc_const_unstable(feature = "const_str_from_utf8", issue = "91006")]
76     #[must_use]
77     #[inline]
78     pub const fn valid_up_to(&self) -> usize {
79         self.valid_up_to
80     }
81
82     /// Provides more information about the failure:
83     ///
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.
88     ///
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
94     ///   lossy decoding.
95     ///
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")]
99     #[must_use]
100     #[inline]
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),
105             None => None,
106         }
107     }
108 }
109
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 {
114             write!(
115                 f,
116                 "invalid utf-8 sequence of {} bytes from index {}",
117                 error_len, self.valid_up_to
118             )
119         } else {
120             write!(f, "incomplete utf-8 byte sequence from index {}", self.valid_up_to)
121         }
122     }
123 }
124
125 /// An error returned when parsing a `bool` using [`from_str`] fails
126 ///
127 /// [`from_str`]: super::FromStr::from_str
128 #[derive(Debug, Clone, PartialEq, Eq)]
129 #[non_exhaustive]
130 #[stable(feature = "rust1", since = "1.0.0")]
131 pub struct ParseBoolError;
132
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)
137     }
138 }