jiff/
error.rs

1use crate::{shared::util::error::Error as SharedError, util::sync::Arc};
2
3/// Creates a new ad hoc error with no causal chain.
4///
5/// This accepts the same arguments as the `format!` macro. The error it
6/// creates is just a wrapper around the string created by `format!`.
7macro_rules! err {
8    ($($tt:tt)*) => {{
9        crate::error::Error::adhoc_from_args(format_args!($($tt)*))
10    }}
11}
12
13pub(crate) use err;
14
15/// An error that can occur in this crate.
16///
17/// The most common type of error is a result of overflow. But other errors
18/// exist as well:
19///
20/// * Time zone database lookup failure.
21/// * Configuration problem. (For example, trying to round a span with calendar
22/// units without providing a relative datetime.)
23/// * An I/O error as a result of trying to open a time zone database from a
24/// directory via
25/// [`TimeZoneDatabase::from_dir`](crate::tz::TimeZoneDatabase::from_dir).
26/// * Parse errors.
27///
28/// # Introspection is limited
29///
30/// Other than implementing the [`std::error::Error`] trait when the
31/// `std` feature is enabled, the [`core::fmt::Debug`] trait and the
32/// [`core::fmt::Display`] trait, this error type currently provides no
33/// introspection capabilities.
34///
35/// # Design
36///
37/// This crate follows the "One True God Error Type Pattern," where only one
38/// error type exists for a variety of different operations. This design was
39/// chosen after attempting to provide finer grained error types. But finer
40/// grained error types proved difficult in the face of composition.
41///
42/// More about this design choice can be found in a GitHub issue
43/// [about error types].
44///
45/// [about error types]: https://github.com/BurntSushi/jiff/issues/8
46#[derive(Clone)]
47pub struct Error {
48    /// The internal representation of an error.
49    ///
50    /// This is in an `Arc` to make an `Error` cloneable. It could otherwise
51    /// be automatically cloneable, but it embeds a `std::io::Error` when the
52    /// `std` feature is enabled, which isn't cloneable.
53    ///
54    /// This also makes clones cheap. And it also make the size of error equal
55    /// to one word (although a `Box` would achieve that last goal). This is
56    /// why we put the `Arc` here instead of on `std::io::Error` directly.
57    inner: Option<Arc<ErrorInner>>,
58}
59
60#[derive(Debug)]
61#[cfg_attr(not(feature = "alloc"), derive(Clone))]
62struct ErrorInner {
63    kind: ErrorKind,
64    #[cfg(feature = "alloc")]
65    cause: Option<Error>,
66}
67
68/// The underlying kind of a [`Error`].
69#[derive(Debug)]
70#[cfg_attr(not(feature = "alloc"), derive(Clone))]
71enum ErrorKind {
72    /// An ad hoc error that is constructed from anything that implements
73    /// the `core::fmt::Display` trait.
74    ///
75    /// In theory we try to avoid these, but they tend to be awfully
76    /// convenient. In practice, we use them a lot, and only use a structured
77    /// representation when a lot of different error cases fit neatly into a
78    /// structure (like range errors).
79    Adhoc(AdhocError),
80    /// An error that occurs when a number is not within its allowed range.
81    ///
82    /// This can occur directly as a result of a number provided by the caller
83    /// of a public API, or as a result of an operation on a number that
84    /// results in it being out of range.
85    Range(RangeError),
86    /// An error that occurs within `jiff::shared`.
87    ///
88    /// It has its own error type to avoid bringing in this much bigger error
89    /// type.
90    Shared(SharedError),
91    /// An error associated with a file path.
92    ///
93    /// This is generally expected to always have a cause attached to it
94    /// explaining what went wrong. The error variant is just a path to make
95    /// it composable with other error types.
96    ///
97    /// The cause is typically `Adhoc` or `IO`.
98    ///
99    /// When `std` is not enabled, this variant can never be constructed.
100    #[allow(dead_code)] // not used in some feature configs
101    FilePath(FilePathError),
102    /// An error that occurs when interacting with the file system.
103    ///
104    /// This is effectively a wrapper around `std::io::Error` coupled with a
105    /// `std::path::PathBuf`.
106    ///
107    /// When `std` is not enabled, this variant can never be constructed.
108    #[allow(dead_code)] // not used in some feature configs
109    IO(IOError),
110}
111
112impl Error {
113    /// Creates a new "ad hoc" error value.
114    ///
115    /// An ad hoc error value is just an opaque string. In theory we should
116    /// avoid creating such error values, but in practice, they are extremely
117    /// convenient. And the alternative is quite brutal given the varied ways
118    /// in which things in a datetime library can fail. (Especially parsing
119    /// errors.)
120    #[cfg(feature = "alloc")]
121    pub(crate) fn adhoc<'a>(message: impl core::fmt::Display + 'a) -> Error {
122        Error::from(ErrorKind::Adhoc(AdhocError::from_display(message)))
123    }
124
125    /// Like `Error::adhoc`, but accepts a `core::fmt::Arguments`.
126    ///
127    /// This is used with the `err!` macro so that we can thread a
128    /// `core::fmt::Arguments` down. This lets us extract a `&'static str`
129    /// from some messages in core-only mode and provide somewhat decent error
130    /// messages in some cases.
131    pub(crate) fn adhoc_from_args<'a>(
132        message: core::fmt::Arguments<'a>,
133    ) -> Error {
134        Error::from(ErrorKind::Adhoc(AdhocError::from_args(message)))
135    }
136
137    /// Like `Error::adhoc`, but creates an error from a `&'static str`
138    /// directly.
139    ///
140    /// This is useful in contexts where you know you have a `&'static str`,
141    /// and avoids relying on `alloc`-only routines like `Error::adhoc`.
142    pub(crate) fn adhoc_from_static_str(message: &'static str) -> Error {
143        Error::from(ErrorKind::Adhoc(AdhocError::from_static_str(message)))
144    }
145
146    /// Creates a new error indicating that a `given` value is out of the
147    /// specified `min..=max` range. The given `what` label is used in the
148    /// error message as a human readable description of what exactly is out
149    /// of range. (e.g., "seconds")
150    pub(crate) fn range(
151        what: &'static str,
152        given: impl Into<i128>,
153        min: impl Into<i128>,
154        max: impl Into<i128>,
155    ) -> Error {
156        Error::from(ErrorKind::Range(RangeError::new(what, given, min, max)))
157    }
158
159    /// Creates a new error from the special "shared" error type.
160    pub(crate) fn shared(err: SharedError) -> Error {
161        Error::from(ErrorKind::Shared(err))
162    }
163
164    /// A convenience constructor for building an I/O error.
165    ///
166    /// This returns an error that is just a simple wrapper around the
167    /// `std::io::Error` type. In general, callers should alwasys attach some
168    /// kind of context to this error (like a file path).
169    ///
170    /// This is only available when the `std` feature is enabled.
171    #[cfg(feature = "std")]
172    pub(crate) fn io(err: std::io::Error) -> Error {
173        Error::from(ErrorKind::IO(IOError { err }))
174    }
175
176    /// Contextualizes this error by associating the given file path with it.
177    ///
178    /// This is a convenience routine for calling `Error::context` with a
179    /// `FilePathError`.
180    ///
181    /// This is only available when the `std` feature is enabled.
182    #[cfg(feature = "tzdb-zoneinfo")]
183    pub(crate) fn path(self, path: impl Into<std::path::PathBuf>) -> Error {
184        let err = Error::from(ErrorKind::FilePath(FilePathError {
185            path: path.into(),
186        }));
187        self.context(err)
188    }
189
190    /*
191    /// Creates a new "unknown" Jiff error.
192    ///
193    /// The benefit of this API is that it permits creating an `Error` in a
194    /// `const` context. But the error message quality is currently pretty
195    /// bad: it's just a generic "unknown jiff error" message.
196    ///
197    /// This could be improved to take a `&'static str`, but I believe this
198    /// will require pointer tagging in order to avoid increasing the size of
199    /// `Error`. (Which is important, because of how many perf sensitive
200    /// APIs return a `Result<T, Error>` in Jiff.
201    pub(crate) const fn unknown() -> Error {
202        Error { inner: None }
203    }
204    */
205}
206
207#[cfg(feature = "std")]
208impl std::error::Error for Error {}
209
210impl core::fmt::Display for Error {
211    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
212        #[cfg(feature = "alloc")]
213        {
214            let mut err = self;
215            loop {
216                let Some(ref inner) = err.inner else {
217                    write!(f, "unknown jiff error")?;
218                    break;
219                };
220                write!(f, "{}", inner.kind)?;
221                err = match inner.cause.as_ref() {
222                    None => break,
223                    Some(err) => err,
224                };
225                write!(f, ": ")?;
226            }
227            Ok(())
228        }
229        #[cfg(not(feature = "alloc"))]
230        {
231            match self.inner {
232                None => write!(f, "unknown jiff error"),
233                Some(ref inner) => write!(f, "{}", inner.kind),
234            }
235        }
236    }
237}
238
239impl core::fmt::Debug for Error {
240    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
241        if !f.alternate() {
242            core::fmt::Display::fmt(self, f)
243        } else {
244            let Some(ref inner) = self.inner else {
245                return f
246                    .debug_struct("Error")
247                    .field("kind", &"None")
248                    .finish();
249            };
250            #[cfg(feature = "alloc")]
251            {
252                f.debug_struct("Error")
253                    .field("kind", &inner.kind)
254                    .field("cause", &inner.cause)
255                    .finish()
256            }
257            #[cfg(not(feature = "alloc"))]
258            {
259                f.debug_struct("Error").field("kind", &inner.kind).finish()
260            }
261        }
262    }
263}
264
265impl core::fmt::Display for ErrorKind {
266    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
267        match *self {
268            ErrorKind::Adhoc(ref msg) => msg.fmt(f),
269            ErrorKind::Range(ref err) => err.fmt(f),
270            ErrorKind::Shared(ref err) => err.fmt(f),
271            ErrorKind::FilePath(ref err) => err.fmt(f),
272            ErrorKind::IO(ref err) => err.fmt(f),
273        }
274    }
275}
276
277impl From<ErrorKind> for Error {
278    fn from(kind: ErrorKind) -> Error {
279        #[cfg(feature = "alloc")]
280        {
281            Error { inner: Some(Arc::new(ErrorInner { kind, cause: None })) }
282        }
283        #[cfg(not(feature = "alloc"))]
284        {
285            Error { inner: Some(Arc::new(ErrorInner { kind })) }
286        }
287    }
288}
289
290/// A generic error message.
291///
292/// This somewhat unfortunately represents most of the errors in Jiff. When I
293/// first started building Jiff, I had a goal of making every error structured.
294/// But this ended up being a ton of work, and I find it much easier and nicer
295/// for error messages to be embedded where they occur.
296#[cfg_attr(not(feature = "alloc"), derive(Clone))]
297struct AdhocError {
298    #[cfg(feature = "alloc")]
299    message: alloc::boxed::Box<str>,
300    #[cfg(not(feature = "alloc"))]
301    message: &'static str,
302}
303
304impl AdhocError {
305    #[cfg(feature = "alloc")]
306    fn from_display<'a>(message: impl core::fmt::Display + 'a) -> AdhocError {
307        use alloc::string::ToString;
308
309        let message = message.to_string().into_boxed_str();
310        AdhocError { message }
311    }
312
313    fn from_args<'a>(message: core::fmt::Arguments<'a>) -> AdhocError {
314        #[cfg(feature = "alloc")]
315        {
316            AdhocError::from_display(message)
317        }
318        #[cfg(not(feature = "alloc"))]
319        {
320            let message = message.as_str().unwrap_or(
321                "unknown Jiff error (better error messages require \
322                 enabling the `alloc` feature for the `jiff` crate)",
323            );
324            AdhocError::from_static_str(message)
325        }
326    }
327
328    fn from_static_str(message: &'static str) -> AdhocError {
329        #[cfg(feature = "alloc")]
330        {
331            AdhocError::from_display(message)
332        }
333        #[cfg(not(feature = "alloc"))]
334        {
335            AdhocError { message }
336        }
337    }
338}
339
340#[cfg(feature = "std")]
341impl std::error::Error for AdhocError {}
342
343impl core::fmt::Display for AdhocError {
344    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
345        core::fmt::Display::fmt(&self.message, f)
346    }
347}
348
349impl core::fmt::Debug for AdhocError {
350    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
351        core::fmt::Debug::fmt(&self.message, f)
352    }
353}
354
355/// An error that occurs when an input value is out of bounds.
356///
357/// The error message produced by this type will include a name describing
358/// which input was out of bounds, the value given and its minimum and maximum
359/// allowed values.
360#[derive(Debug)]
361#[cfg_attr(not(feature = "alloc"), derive(Clone))]
362struct RangeError {
363    what: &'static str,
364    #[cfg(feature = "alloc")]
365    given: i128,
366    #[cfg(feature = "alloc")]
367    min: i128,
368    #[cfg(feature = "alloc")]
369    max: i128,
370}
371
372impl RangeError {
373    fn new(
374        what: &'static str,
375        _given: impl Into<i128>,
376        _min: impl Into<i128>,
377        _max: impl Into<i128>,
378    ) -> RangeError {
379        RangeError {
380            what,
381            #[cfg(feature = "alloc")]
382            given: _given.into(),
383            #[cfg(feature = "alloc")]
384            min: _min.into(),
385            #[cfg(feature = "alloc")]
386            max: _max.into(),
387        }
388    }
389}
390
391#[cfg(feature = "std")]
392impl std::error::Error for RangeError {}
393
394impl core::fmt::Display for RangeError {
395    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
396        #[cfg(feature = "alloc")]
397        {
398            let RangeError { what, given, min, max } = *self;
399            write!(
400                f,
401                "parameter '{what}' with value {given} \
402                 is not in the required range of {min}..={max}",
403            )
404        }
405        #[cfg(not(feature = "alloc"))]
406        {
407            let RangeError { what } = *self;
408            write!(f, "parameter '{what}' is not in the required range")
409        }
410    }
411}
412
413/// A `std::io::Error`.
414///
415/// This type is itself always available, even when the `std` feature is not
416/// enabled. When `std` is not enabled, a value of this type can never be
417/// constructed.
418///
419/// Otherwise, this type is a simple wrapper around `std::io::Error`. Its
420/// purpose is to encapsulate the conditional compilation based on the `std`
421/// feature.
422#[cfg_attr(not(feature = "alloc"), derive(Clone))]
423struct IOError {
424    #[cfg(feature = "std")]
425    err: std::io::Error,
426}
427
428#[cfg(feature = "std")]
429impl std::error::Error for IOError {}
430
431impl core::fmt::Display for IOError {
432    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
433        #[cfg(feature = "std")]
434        {
435            write!(f, "{}", self.err)
436        }
437        #[cfg(not(feature = "std"))]
438        {
439            write!(f, "<BUG: SHOULD NOT EXIST>")
440        }
441    }
442}
443
444impl core::fmt::Debug for IOError {
445    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
446        #[cfg(feature = "std")]
447        {
448            f.debug_struct("IOError").field("err", &self.err).finish()
449        }
450        #[cfg(not(feature = "std"))]
451        {
452            write!(f, "<BUG: SHOULD NOT EXIST>")
453        }
454    }
455}
456
457#[cfg(feature = "std")]
458impl From<std::io::Error> for IOError {
459    fn from(err: std::io::Error) -> IOError {
460        IOError { err }
461    }
462}
463
464#[cfg_attr(not(feature = "alloc"), derive(Clone))]
465struct FilePathError {
466    #[cfg(feature = "std")]
467    path: std::path::PathBuf,
468}
469
470#[cfg(feature = "std")]
471impl std::error::Error for FilePathError {}
472
473impl core::fmt::Display for FilePathError {
474    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
475        #[cfg(feature = "std")]
476        {
477            write!(f, "{}", self.path.display())
478        }
479        #[cfg(not(feature = "std"))]
480        {
481            write!(f, "<BUG: SHOULD NOT EXIST>")
482        }
483    }
484}
485
486impl core::fmt::Debug for FilePathError {
487    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
488        #[cfg(feature = "std")]
489        {
490            f.debug_struct("FilePathError").field("path", &self.path).finish()
491        }
492        #[cfg(not(feature = "std"))]
493        {
494            write!(f, "<BUG: SHOULD NOT EXIST>")
495        }
496    }
497}
498
499/// A simple trait to encapsulate automatic conversion to `Error`.
500///
501/// This trait basically exists to make `Error::context` work without needing
502/// to rely on public `From` impls. For example, without this trait, we might
503/// otherwise write `impl From<String> for Error`. But this would make it part
504/// of the public API. Which... maybe we should do, but at time of writing,
505/// I'm starting very conservative so that we can evolve errors in semver
506/// compatible ways.
507pub(crate) trait IntoError {
508    fn into_error(self) -> Error;
509}
510
511impl IntoError for Error {
512    fn into_error(self) -> Error {
513        self
514    }
515}
516
517impl IntoError for &'static str {
518    fn into_error(self) -> Error {
519        Error::adhoc_from_static_str(self)
520    }
521}
522
523#[cfg(feature = "alloc")]
524impl IntoError for alloc::string::String {
525    fn into_error(self) -> Error {
526        Error::adhoc(self)
527    }
528}
529
530/// A trait for contextualizing error values.
531///
532/// This makes it easy to contextualize either `Error` or `Result<T, Error>`.
533/// Specifically, in the latter case, it absolves one of the need to call
534/// `map_err` everywhere one wants to add context to an error.
535///
536/// This trick was borrowed from `anyhow`.
537pub(crate) trait ErrorContext {
538    /// Contextualize the given consequent error with this (`self`) error as
539    /// the cause.
540    ///
541    /// This is equivalent to saying that "consequent is caused by self."
542    ///
543    /// Note that if an `Error` is given for `kind`, then this panics if it has
544    /// a cause. (Because the cause would otherwise be dropped. An error causal
545    /// chain is just a linked list, not a tree.)
546    fn context(self, consequent: impl IntoError) -> Self;
547
548    /// Like `context`, but hides error construction within a closure.
549    ///
550    /// This is useful if the creation of the consequent error is not otherwise
551    /// guarded and when error construction is potentially "costly" (i.e., it
552    /// allocates). The closure avoids paying the cost of contextual error
553    /// creation in the happy path.
554    ///
555    /// Usually this only makes sense to use on a `Result<T, Error>`, otherwise
556    /// the closure is just executed immediately anyway.
557    fn with_context<E: IntoError>(
558        self,
559        consequent: impl FnOnce() -> E,
560    ) -> Self;
561}
562
563impl ErrorContext for Error {
564    #[cfg_attr(feature = "perf-inline", inline(always))]
565    fn context(self, consequent: impl IntoError) -> Error {
566        #[cfg(feature = "alloc")]
567        {
568            let mut err = consequent.into_error();
569            if err.inner.is_none() {
570                err = err!("unknown jiff error");
571            }
572            let inner = err.inner.as_mut().unwrap();
573            assert!(
574                inner.cause.is_none(),
575                "cause of consequence must be `None`"
576            );
577            // OK because we just created this error so the Arc
578            // has one reference.
579            Arc::get_mut(inner).unwrap().cause = Some(self);
580            err
581        }
582        #[cfg(not(feature = "alloc"))]
583        {
584            // We just completely drop `self`. :-(
585            consequent.into_error()
586        }
587    }
588
589    #[cfg_attr(feature = "perf-inline", inline(always))]
590    fn with_context<E: IntoError>(
591        self,
592        consequent: impl FnOnce() -> E,
593    ) -> Error {
594        #[cfg(feature = "alloc")]
595        {
596            let mut err = consequent().into_error();
597            if err.inner.is_none() {
598                err = err!("unknown jiff error");
599            }
600            let inner = err.inner.as_mut().unwrap();
601            assert!(
602                inner.cause.is_none(),
603                "cause of consequence must be `None`"
604            );
605            // OK because we just created this error so the Arc
606            // has one reference.
607            Arc::get_mut(inner).unwrap().cause = Some(self);
608            err
609        }
610        #[cfg(not(feature = "alloc"))]
611        {
612            // We just completely drop `self`. :-(
613            consequent().into_error()
614        }
615    }
616}
617
618impl<T> ErrorContext for Result<T, Error> {
619    #[cfg_attr(feature = "perf-inline", inline(always))]
620    fn context(self, consequent: impl IntoError) -> Result<T, Error> {
621        self.map_err(|err| err.context(consequent))
622    }
623
624    #[cfg_attr(feature = "perf-inline", inline(always))]
625    fn with_context<E: IntoError>(
626        self,
627        consequent: impl FnOnce() -> E,
628    ) -> Result<T, Error> {
629        self.map_err(|err| err.with_context(consequent))
630    }
631}
632
633#[cfg(test)]
634mod tests {
635    use super::*;
636
637    // We test that our 'Error' type is the size we expect. This isn't an API
638    // guarantee, but if the size increases, we really want to make sure we
639    // decide to do that intentionally. So this should be a speed bump. And in
640    // general, we should not increase the size without a very good reason.
641    #[test]
642    fn error_size() {
643        let mut expected_size = core::mem::size_of::<usize>();
644        if !cfg!(feature = "alloc") {
645            // oooowwwwwwwwwwwch.
646            //
647            // Like, this is horrible, right? core-only environments are
648            // precisely the place where one want to keep things slim. But
649            // in core-only, I don't know of a way to introduce any sort of
650            // indirection in the library level without using a completely
651            // different API.
652            //
653            // This is what makes me doubt that core-only Jiff is actually
654            // useful. In what context are people using a huge library like
655            // Jiff but can't define a small little heap allocator?
656            //
657            // OK, this used to be `expected_size *= 10`, but I slimmed it down
658            // to x3. Still kinda sucks right? If we tried harder, I think we
659            // could probably slim this down more. And if we were willing to
660            // sacrifice error message quality even more (like, all the way),
661            // then we could make `Error` a zero sized type. Which might
662            // actually be the right trade-off for core-only, but I'll hold off
663            // until we have some real world use cases.
664            expected_size *= 3;
665        }
666        assert_eq!(expected_size, core::mem::size_of::<Error>());
667    }
668}