const_format/fmt/
error.rs

1// <_< clippy you silly
2#![allow(clippy::enum_variant_names)]
3
4use core::fmt::{self, Display};
5
6/// An error while trying to write into a StrWriter.
7#[non_exhaustive]
8#[derive(Debug, Copy, Clone, PartialEq, Eq)]
9pub enum Error {
10    /// Attempted to write something into the buffer when there isn't enough space to write it.
11    NotEnoughSpace,
12    /// For compatibility with [`NotAsciiError`](../wrapper_types/struct.NotAsciiError.html)
13    NotAscii,
14    /// Attempted to index a string arguent by an range where one of the bounds
15    /// was not on a char boundary.
16    NotOnCharBoundary,
17}
18
19impl Display for Error {
20    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
21        match self {
22            Self::NotEnoughSpace => {
23                fmt.write_str("The was not enough space to write the formatted output")
24            }
25            Self::NotAscii => fmt.write_str("Attempted to write non-ascii text"),
26            Self::NotOnCharBoundary => {
27                fmt.write_str("Attempted to index a byte that's not on a char boundary.")
28            }
29        }
30    }
31}
32
33macro_rules! index_vars{
34    ($self:ident, $index:ident; $($variant:ident),* $(,)? ) => (
35        enum Index{
36            $($variant,)*
37        }
38
39        let $index = match &$self {
40            $(Error::$variant{..} => 3300 + Index::$variant as usize,)*
41        };
42    )
43}
44
45impl Error {
46    /// For panicking at compile-time, with a compile-time error that says what the error is.
47    #[track_caller]
48    pub const fn unwrap<T>(&self) -> T {
49        index_vars! {
50            self,i;
51            NotEnoughSpace,
52            NotAscii,
53            NotOnCharBoundary,
54        };
55
56        match self {
57            Error::NotEnoughSpace => ["The was not enough space to write the formatted output"][i],
58            Error::NotAscii => ["Attempted to write non-ascii text"][i],
59            Error::NotOnCharBoundary => {
60                ["Attempted to index a byte that's not on a char boundary."][i]
61            }
62        };
63        loop {}
64    }
65}
66
67////////////////////////////////////////////////////////////////////////////////
68
69/// The return type of most formatting functions
70pub type Result<T = (), E = Error> = core::result::Result<T, E>;
71
72////////////////////////////////////////////////////////////////////////////////
73
74/// For converting types to [`const_format::Result`]
75///
76/// [`const_format::Result`]: ./type.Result.html
77pub struct ToResult<T>(pub T);
78
79impl ToResult<()> {
80    ///
81    #[inline(always)]
82    pub const fn to_result(self) -> Result {
83        Ok(())
84    }
85}
86
87impl ToResult<Result> {
88    ///
89    #[inline(always)]
90    pub const fn to_result(self) -> Result {
91        self.0
92    }
93}