bump_scope/from_utf8_error.rs
1use core::{error::Error, fmt, ops::Deref, str::Utf8Error};
2
3/// A possible error value when converting a string from a UTF-8 byte vector.
4///
5/// This type is the error type for [`BumpString::from_utf8`](crate::BumpString::from_utf8), [`MutBumpString::from_utf8`](crate::MutBumpString::from_utf8) and [`BumpBox<str>::from_utf8`](crate::BumpBox::from_utf8). It
6/// is designed in such a way to carefully avoid reallocations: the
7/// [`into_bytes`](FromUtf8Error::into_bytes) method will give back the byte vector that was used in the
8/// conversion attempt.
9///
10/// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
11/// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
12/// an analogue to `FromUtf8Error`, and you can get one from a `FromUtf8Error`
13/// through the [`utf8_error`] method.
14///
15/// [`Utf8Error`]: core::str::Utf8Error
16/// [`std::str`]: core::str "std::str"
17/// [`&str`]: prim@str "&str"
18/// [`utf8_error`]: FromUtf8Error::utf8_error
19#[derive(Debug, PartialEq, Eq)]
20#[cfg_attr(feature = "panic-on-alloc", derive(Clone))]
21pub struct FromUtf8Error<Bytes> {
22    bytes: Bytes,
23    error: Utf8Error,
24}
25
26impl<Bytes> FromUtf8Error<Bytes> {
27    #[inline(always)]
28    pub(crate) const fn new(error: Utf8Error, bytes: Bytes) -> Self {
29        Self { bytes, error }
30    }
31
32    /// Returns a slice of [`u8`]s bytes that were attempted to convert to a `String`.
33    #[must_use]
34    #[inline(always)]
35    pub fn as_bytes(&self) -> &[u8]
36    where
37        Bytes: Deref<Target = [u8]>,
38    {
39        &self.bytes
40    }
41
42    /// Returns the bytes that were attempted to convert to a `String`.
43    #[must_use = "`self` will be dropped if the result is not used"]
44    #[inline(always)]
45    pub fn into_bytes(self) -> Bytes {
46        self.bytes
47    }
48
49    /// Fetch a `Utf8Error` to get more details about the conversion failure.
50    ///
51    /// The [`Utf8Error`] type provided by [`std::str`] represents an error that may
52    /// occur when converting a slice of [`u8`]s to a [`&str`]. In this sense, it's
53    /// an analogue to `FromUtf8Error`. See its documentation for more details
54    /// on using it.
55    ///
56    /// [`std::str`]: core::str "std::str"
57    /// [`&str`]: prim@str "&str"
58    #[inline(always)]
59    pub fn utf8_error(&self) -> Utf8Error {
60        self.error
61    }
62}
63
64impl<Bytes> fmt::Display for FromUtf8Error<Bytes> {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        fmt::Display::fmt(&self.error, f)
67    }
68}
69
70impl<Bytes: fmt::Debug> Error for FromUtf8Error<Bytes> {}