lerror/
lib.rs

1mod context;
2mod ensure;
3mod error;
4mod fmt;
5mod macros;
6use std::{collections::LinkedList, error::Error as StdError, fmt::Display};
7
8extern crate alloc;
9
10use error::ContextError;
11
12#[repr(transparent)]
13pub struct Error {
14    inner: LinkedList<ContextError<String>>,
15}
16
17#[doc(no_inline)]
18pub use lerror as format_err;
19
20pub type Result<T, E = Error> = core::result::Result<T, E>;
21
22pub trait Context<T, E>: crate::context::private::Sealed {
23    /// Wrap the error value with additional context.
24    fn context<C>(self, context: C) -> Result<T, Error>
25    where
26        C: Display + Send + Sync + 'static;
27
28    /// Wrap the error value with additional context that is evaluated lazily
29    /// only once an error does occur.
30    fn with_context<C, F>(self, f: F) -> Result<T, Error>
31    where
32        C: Display + Send + Sync + 'static,
33        F: FnOnce() -> C;
34}
35
36pub trait ContextExt<T, E>: Context<T, E> {
37    /// c is a shorthand for `context`. It adds location information to the error.
38    fn c(self) -> Result<T, Error>;
39}
40
41#[allow(non_snake_case)]
42pub fn Ok<T>(t: T) -> Result<T> {
43    Result::Ok(t)
44}
45
46// Not public API. Referenced by macro-generated code.
47#[doc(hidden)]
48pub mod __private {
49    use crate::Error;
50    use alloc::fmt;
51    use core::fmt::Arguments;
52
53    #[doc(hidden)]
54    pub use crate::ensure::{BothDebug, NotBothDebug};
55    #[doc(hidden)]
56    pub use alloc::format;
57    #[doc(hidden)]
58    pub use core::result::Result::Err;
59    #[doc(hidden)]
60    pub use core::{concat, format_args, stringify};
61
62    #[doc(hidden)]
63    #[inline]
64    #[cold]
65    #[track_caller]
66    pub fn format_err(args: Arguments) -> Error {
67        let fmt_arguments_as_str = args.as_str();
68
69        if let Some(message) = fmt_arguments_as_str {
70            // anyhow!("literal"), can downcast to &'static str
71            Error::from_display(message)
72        } else {
73            // anyhow!("interpolate {var}"), can downcast to String
74            Error::from_display(fmt::format(args))
75        }
76    }
77
78    #[doc(hidden)]
79    #[inline]
80    #[cold]
81    #[must_use]
82    pub fn must_use(error: Error) -> Error {
83        error
84    }
85}