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 error value from `core::fmt::Arguments`.
114    ///
115    /// It is expected to use [`format_args!`](format_args) from
116    /// Rust's standard library (available in `core`) to create a
117    /// `core::fmt::Arguments`.
118    ///
119    /// Callers should generally use their own error types. But in some
120    /// circumstances, it can be convenient to manufacture a Jiff error value
121    /// specifically.
122    ///
123    /// # Example
124    ///
125    /// ```
126    /// use jiff::Error;
127    ///
128    /// let err = Error::from_args(format_args!("something failed"));
129    /// assert_eq!(err.to_string(), "something failed");
130    /// ```
131    pub fn from_args<'a>(message: core::fmt::Arguments<'a>) -> Error {
132        Error::from(ErrorKind::Adhoc(AdhocError::from_args(message)))
133    }
134
135    #[inline(never)]
136    #[cold]
137    fn context_impl(self, consequent: Error) -> Error {
138        #[cfg(feature = "alloc")]
139        {
140            let mut err = consequent;
141            if err.inner.is_none() {
142                err = err!("unknown jiff error");
143            }
144            let inner = err.inner.as_mut().unwrap();
145            assert!(
146                inner.cause.is_none(),
147                "cause of consequence must be `None`"
148            );
149            // OK because we just created this error so the Arc
150            // has one reference.
151            Arc::get_mut(inner).unwrap().cause = Some(self);
152            err
153        }
154        #[cfg(not(feature = "alloc"))]
155        {
156            // We just completely drop `self`. :-(
157            consequent
158        }
159    }
160}
161
162impl Error {
163    /// Creates a new "ad hoc" error value.
164    ///
165    /// An ad hoc error value is just an opaque string.
166    #[cfg(feature = "alloc")]
167    #[inline(never)]
168    #[cold]
169    pub(crate) fn adhoc<'a>(message: impl core::fmt::Display + 'a) -> Error {
170        Error::from(ErrorKind::Adhoc(AdhocError::from_display(message)))
171    }
172
173    /// Like `Error::adhoc`, but accepts a `core::fmt::Arguments`.
174    ///
175    /// This is used with the `err!` macro so that we can thread a
176    /// `core::fmt::Arguments` down. This lets us extract a `&'static str`
177    /// from some messages in core-only mode and provide somewhat decent error
178    /// messages in some cases.
179    #[inline(never)]
180    #[cold]
181    pub(crate) fn adhoc_from_args<'a>(
182        message: core::fmt::Arguments<'a>,
183    ) -> Error {
184        Error::from(ErrorKind::Adhoc(AdhocError::from_args(message)))
185    }
186
187    /// Like `Error::adhoc`, but creates an error from a `String` directly.
188    ///
189    /// This exists to explicitly monomorphize a very common case.
190    #[cfg(feature = "alloc")]
191    #[inline(never)]
192    #[cold]
193    fn adhoc_from_string(message: alloc::string::String) -> Error {
194        Error::adhoc(message)
195    }
196
197    /// Like `Error::adhoc`, but creates an error from a `&'static str`
198    /// directly.
199    ///
200    /// This is useful in contexts where you know you have a `&'static str`,
201    /// and avoids relying on `alloc`-only routines like `Error::adhoc`.
202    #[inline(never)]
203    #[cold]
204    pub(crate) fn adhoc_from_static_str(message: &'static str) -> Error {
205        Error::from(ErrorKind::Adhoc(AdhocError::from_static_str(message)))
206    }
207
208    /// Creates a new error indicating that a `given` value is out of the
209    /// specified `min..=max` range. The given `what` label is used in the
210    /// error message as a human readable description of what exactly is out
211    /// of range. (e.g., "seconds")
212    #[inline(never)]
213    #[cold]
214    pub(crate) fn range(
215        what: &'static str,
216        given: impl Into<i128>,
217        min: impl Into<i128>,
218        max: impl Into<i128>,
219    ) -> Error {
220        Error::from(ErrorKind::Range(RangeError::new(what, given, min, max)))
221    }
222
223    /// Creates a new error from the special "shared" error type.
224    pub(crate) fn shared(err: SharedError) -> Error {
225        Error::from(ErrorKind::Shared(err))
226    }
227
228    /// A convenience constructor for building an I/O error.
229    ///
230    /// This returns an error that is just a simple wrapper around the
231    /// `std::io::Error` type. In general, callers should alwasys attach some
232    /// kind of context to this error (like a file path).
233    ///
234    /// This is only available when the `std` feature is enabled.
235    #[cfg(feature = "std")]
236    #[inline(never)]
237    #[cold]
238    pub(crate) fn io(err: std::io::Error) -> Error {
239        Error::from(ErrorKind::IO(IOError { err }))
240    }
241
242    /// Contextualizes this error by associating the given file path with it.
243    ///
244    /// This is a convenience routine for calling `Error::context` with a
245    /// `FilePathError`.
246    #[cfg(any(feature = "tzdb-zoneinfo", feature = "tzdb-concatenated"))]
247    #[inline(never)]
248    #[cold]
249    pub(crate) fn path(self, path: impl Into<std::path::PathBuf>) -> Error {
250        let err = Error::from(ErrorKind::FilePath(FilePathError {
251            path: path.into(),
252        }));
253        self.context(err)
254    }
255
256    /*
257    /// Creates a new "unknown" Jiff error.
258    ///
259    /// The benefit of this API is that it permits creating an `Error` in a
260    /// `const` context. But the error message quality is currently pretty
261    /// bad: it's just a generic "unknown jiff error" message.
262    ///
263    /// This could be improved to take a `&'static str`, but I believe this
264    /// will require pointer tagging in order to avoid increasing the size of
265    /// `Error`. (Which is important, because of how many perf sensitive
266    /// APIs return a `Result<T, Error>` in Jiff.
267    pub(crate) const fn unknown() -> Error {
268        Error { inner: None }
269    }
270    */
271}
272
273#[cfg(feature = "std")]
274impl std::error::Error for Error {}
275
276impl core::fmt::Display for Error {
277    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
278        #[cfg(feature = "alloc")]
279        {
280            let mut err = self;
281            loop {
282                let Some(ref inner) = err.inner else {
283                    write!(f, "unknown jiff error")?;
284                    break;
285                };
286                write!(f, "{}", inner.kind)?;
287                err = match inner.cause.as_ref() {
288                    None => break,
289                    Some(err) => err,
290                };
291                write!(f, ": ")?;
292            }
293            Ok(())
294        }
295        #[cfg(not(feature = "alloc"))]
296        {
297            match self.inner {
298                None => write!(f, "unknown jiff error"),
299                Some(ref inner) => write!(f, "{}", inner.kind),
300            }
301        }
302    }
303}
304
305impl core::fmt::Debug for Error {
306    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
307        if !f.alternate() {
308            core::fmt::Display::fmt(self, f)
309        } else {
310            let Some(ref inner) = self.inner else {
311                return f
312                    .debug_struct("Error")
313                    .field("kind", &"None")
314                    .finish();
315            };
316            #[cfg(feature = "alloc")]
317            {
318                f.debug_struct("Error")
319                    .field("kind", &inner.kind)
320                    .field("cause", &inner.cause)
321                    .finish()
322            }
323            #[cfg(not(feature = "alloc"))]
324            {
325                f.debug_struct("Error").field("kind", &inner.kind).finish()
326            }
327        }
328    }
329}
330
331impl core::fmt::Display for ErrorKind {
332    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
333        match *self {
334            ErrorKind::Adhoc(ref msg) => msg.fmt(f),
335            ErrorKind::Range(ref err) => err.fmt(f),
336            ErrorKind::Shared(ref err) => err.fmt(f),
337            ErrorKind::FilePath(ref err) => err.fmt(f),
338            ErrorKind::IO(ref err) => err.fmt(f),
339        }
340    }
341}
342
343impl From<ErrorKind> for Error {
344    fn from(kind: ErrorKind) -> Error {
345        #[cfg(feature = "alloc")]
346        {
347            Error { inner: Some(Arc::new(ErrorInner { kind, cause: None })) }
348        }
349        #[cfg(not(feature = "alloc"))]
350        {
351            Error { inner: Some(Arc::new(ErrorInner { kind })) }
352        }
353    }
354}
355
356/// A generic error message.
357///
358/// This somewhat unfortunately represents most of the errors in Jiff. When I
359/// first started building Jiff, I had a goal of making every error structured.
360/// But this ended up being a ton of work, and I find it much easier and nicer
361/// for error messages to be embedded where they occur.
362#[cfg_attr(not(feature = "alloc"), derive(Clone))]
363struct AdhocError {
364    #[cfg(feature = "alloc")]
365    message: alloc::boxed::Box<str>,
366    #[cfg(not(feature = "alloc"))]
367    message: &'static str,
368}
369
370impl AdhocError {
371    #[cfg(feature = "alloc")]
372    fn from_display<'a>(message: impl core::fmt::Display + 'a) -> AdhocError {
373        use alloc::string::ToString;
374
375        let message = message.to_string().into_boxed_str();
376        AdhocError { message }
377    }
378
379    fn from_args<'a>(message: core::fmt::Arguments<'a>) -> AdhocError {
380        #[cfg(feature = "alloc")]
381        {
382            AdhocError::from_display(message)
383        }
384        #[cfg(not(feature = "alloc"))]
385        {
386            let message = message.as_str().unwrap_or(
387                "unknown Jiff error (better error messages require \
388                 enabling the `alloc` feature for the `jiff` crate)",
389            );
390            AdhocError::from_static_str(message)
391        }
392    }
393
394    fn from_static_str(message: &'static str) -> AdhocError {
395        #[cfg(feature = "alloc")]
396        {
397            AdhocError::from_display(message)
398        }
399        #[cfg(not(feature = "alloc"))]
400        {
401            AdhocError { message }
402        }
403    }
404}
405
406#[cfg(feature = "std")]
407impl std::error::Error for AdhocError {}
408
409impl core::fmt::Display for AdhocError {
410    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
411        core::fmt::Display::fmt(&self.message, f)
412    }
413}
414
415impl core::fmt::Debug for AdhocError {
416    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
417        core::fmt::Debug::fmt(&self.message, f)
418    }
419}
420
421/// An error that occurs when an input value is out of bounds.
422///
423/// The error message produced by this type will include a name describing
424/// which input was out of bounds, the value given and its minimum and maximum
425/// allowed values.
426#[derive(Debug)]
427#[cfg_attr(not(feature = "alloc"), derive(Clone))]
428struct RangeError {
429    what: &'static str,
430    #[cfg(feature = "alloc")]
431    given: i128,
432    #[cfg(feature = "alloc")]
433    min: i128,
434    #[cfg(feature = "alloc")]
435    max: i128,
436}
437
438impl RangeError {
439    fn new(
440        what: &'static str,
441        _given: impl Into<i128>,
442        _min: impl Into<i128>,
443        _max: impl Into<i128>,
444    ) -> RangeError {
445        RangeError {
446            what,
447            #[cfg(feature = "alloc")]
448            given: _given.into(),
449            #[cfg(feature = "alloc")]
450            min: _min.into(),
451            #[cfg(feature = "alloc")]
452            max: _max.into(),
453        }
454    }
455}
456
457#[cfg(feature = "std")]
458impl std::error::Error for RangeError {}
459
460impl core::fmt::Display for RangeError {
461    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
462        #[cfg(feature = "alloc")]
463        {
464            let RangeError { what, given, min, max } = *self;
465            write!(
466                f,
467                "parameter '{what}' with value {given} \
468                 is not in the required range of {min}..={max}",
469            )
470        }
471        #[cfg(not(feature = "alloc"))]
472        {
473            let RangeError { what } = *self;
474            write!(f, "parameter '{what}' is not in the required range")
475        }
476    }
477}
478
479/// A `std::io::Error`.
480///
481/// This type is itself always available, even when the `std` feature is not
482/// enabled. When `std` is not enabled, a value of this type can never be
483/// constructed.
484///
485/// Otherwise, this type is a simple wrapper around `std::io::Error`. Its
486/// purpose is to encapsulate the conditional compilation based on the `std`
487/// feature.
488#[cfg_attr(not(feature = "alloc"), derive(Clone))]
489struct IOError {
490    #[cfg(feature = "std")]
491    err: std::io::Error,
492}
493
494#[cfg(feature = "std")]
495impl std::error::Error for IOError {}
496
497impl core::fmt::Display for IOError {
498    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
499        #[cfg(feature = "std")]
500        {
501            write!(f, "{}", self.err)
502        }
503        #[cfg(not(feature = "std"))]
504        {
505            write!(f, "<BUG: SHOULD NOT EXIST>")
506        }
507    }
508}
509
510impl core::fmt::Debug for IOError {
511    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
512        #[cfg(feature = "std")]
513        {
514            f.debug_struct("IOError").field("err", &self.err).finish()
515        }
516        #[cfg(not(feature = "std"))]
517        {
518            write!(f, "<BUG: SHOULD NOT EXIST>")
519        }
520    }
521}
522
523#[cfg(feature = "std")]
524impl From<std::io::Error> for IOError {
525    fn from(err: std::io::Error) -> IOError {
526        IOError { err }
527    }
528}
529
530#[cfg_attr(not(feature = "alloc"), derive(Clone))]
531struct FilePathError {
532    #[cfg(feature = "std")]
533    path: std::path::PathBuf,
534}
535
536#[cfg(feature = "std")]
537impl std::error::Error for FilePathError {}
538
539impl core::fmt::Display for FilePathError {
540    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
541        #[cfg(feature = "std")]
542        {
543            write!(f, "{}", self.path.display())
544        }
545        #[cfg(not(feature = "std"))]
546        {
547            write!(f, "<BUG: SHOULD NOT EXIST>")
548        }
549    }
550}
551
552impl core::fmt::Debug for FilePathError {
553    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
554        #[cfg(feature = "std")]
555        {
556            f.debug_struct("FilePathError").field("path", &self.path).finish()
557        }
558        #[cfg(not(feature = "std"))]
559        {
560            write!(f, "<BUG: SHOULD NOT EXIST>")
561        }
562    }
563}
564
565/// A simple trait to encapsulate automatic conversion to `Error`.
566///
567/// This trait basically exists to make `Error::context` work without needing
568/// to rely on public `From` impls. For example, without this trait, we might
569/// otherwise write `impl From<String> for Error`. But this would make it part
570/// of the public API. Which... maybe we should do, but at time of writing,
571/// I'm starting very conservative so that we can evolve errors in semver
572/// compatible ways.
573pub(crate) trait IntoError {
574    fn into_error(self) -> Error;
575}
576
577impl IntoError for Error {
578    #[inline(always)]
579    fn into_error(self) -> Error {
580        self
581    }
582}
583
584impl IntoError for &'static str {
585    #[inline(always)]
586    fn into_error(self) -> Error {
587        Error::adhoc_from_static_str(self)
588    }
589}
590
591#[cfg(feature = "alloc")]
592impl IntoError for alloc::string::String {
593    #[inline(always)]
594    fn into_error(self) -> Error {
595        Error::adhoc_from_string(self)
596    }
597}
598
599/// A trait for contextualizing error values.
600///
601/// This makes it easy to contextualize either `Error` or `Result<T, Error>`.
602/// Specifically, in the latter case, it absolves one of the need to call
603/// `map_err` everywhere one wants to add context to an error.
604///
605/// This trick was borrowed from `anyhow`.
606pub(crate) trait ErrorContext {
607    /// Contextualize the given consequent error with this (`self`) error as
608    /// the cause.
609    ///
610    /// This is equivalent to saying that "consequent is caused by self."
611    ///
612    /// Note that if an `Error` is given for `kind`, then this panics if it has
613    /// a cause. (Because the cause would otherwise be dropped. An error causal
614    /// chain is just a linked list, not a tree.)
615    fn context(self, consequent: impl IntoError) -> Self;
616
617    /// Like `context`, but hides error construction within a closure.
618    ///
619    /// This is useful if the creation of the consequent error is not otherwise
620    /// guarded and when error construction is potentially "costly" (i.e., it
621    /// allocates). The closure avoids paying the cost of contextual error
622    /// creation in the happy path.
623    ///
624    /// Usually this only makes sense to use on a `Result<T, Error>`, otherwise
625    /// the closure is just executed immediately anyway.
626    fn with_context<E: IntoError>(
627        self,
628        consequent: impl FnOnce() -> E,
629    ) -> Self;
630}
631
632impl ErrorContext for Error {
633    #[cfg_attr(feature = "perf-inline", inline(always))]
634    fn context(self, consequent: impl IntoError) -> Error {
635        self.context_impl(consequent.into_error())
636    }
637
638    #[cfg_attr(feature = "perf-inline", inline(always))]
639    fn with_context<E: IntoError>(
640        self,
641        consequent: impl FnOnce() -> E,
642    ) -> Error {
643        self.context_impl(consequent().into_error())
644    }
645}
646
647impl<T> ErrorContext for Result<T, Error> {
648    #[cfg_attr(feature = "perf-inline", inline(always))]
649    fn context(self, consequent: impl IntoError) -> Result<T, Error> {
650        self.map_err(|err| err.context_impl(consequent.into_error()))
651    }
652
653    #[cfg_attr(feature = "perf-inline", inline(always))]
654    fn with_context<E: IntoError>(
655        self,
656        consequent: impl FnOnce() -> E,
657    ) -> Result<T, Error> {
658        self.map_err(|err| err.context_impl(consequent().into_error()))
659    }
660}
661
662#[cfg(test)]
663mod tests {
664    use super::*;
665
666    // We test that our 'Error' type is the size we expect. This isn't an API
667    // guarantee, but if the size increases, we really want to make sure we
668    // decide to do that intentionally. So this should be a speed bump. And in
669    // general, we should not increase the size without a very good reason.
670    #[test]
671    fn error_size() {
672        let mut expected_size = core::mem::size_of::<usize>();
673        if !cfg!(feature = "alloc") {
674            // oooowwwwwwwwwwwch.
675            //
676            // Like, this is horrible, right? core-only environments are
677            // precisely the place where one want to keep things slim. But
678            // in core-only, I don't know of a way to introduce any sort of
679            // indirection in the library level without using a completely
680            // different API.
681            //
682            // This is what makes me doubt that core-only Jiff is actually
683            // useful. In what context are people using a huge library like
684            // Jiff but can't define a small little heap allocator?
685            //
686            // OK, this used to be `expected_size *= 10`, but I slimmed it down
687            // to x3. Still kinda sucks right? If we tried harder, I think we
688            // could probably slim this down more. And if we were willing to
689            // sacrifice error message quality even more (like, all the way),
690            // then we could make `Error` a zero sized type. Which might
691            // actually be the right trade-off for core-only, but I'll hold off
692            // until we have some real world use cases.
693            expected_size *= 3;
694        }
695        assert_eq!(expected_size, core::mem::size_of::<Error>());
696    }
697}