Skip to main content

jiff/error/
mod.rs

1use crate::util::{
2    b::{BoundsError, SpecialBoundsError},
3    sync::Arc,
4};
5
6pub(crate) mod civil;
7pub(crate) mod duration;
8pub(crate) mod fmt;
9pub(crate) mod signed_duration;
10pub(crate) mod span;
11pub(crate) mod timestamp;
12pub(crate) mod tz;
13pub(crate) mod unit;
14pub(crate) mod util;
15pub(crate) mod zoned;
16
17/// An error that can occur in this crate.
18///
19/// The most common type of error is a result of overflow. But other errors
20/// exist as well:
21///
22/// * Time zone database lookup failure.
23/// * Configuration problem. (For example, trying to round a span with calendar
24/// units without providing a relative datetime.)
25/// * An I/O error as a result of trying to open a time zone database from a
26/// directory via
27/// [`TimeZoneDatabase::from_dir`](crate::tz::TimeZoneDatabase::from_dir).
28/// * Parse errors.
29///
30/// # Introspection is limited
31///
32/// Other than implementing the [`core::error::Error`], [`core::fmt::Debug`]
33/// and [`core::fmt::Display`] traits, this error type currently provides very
34/// limited introspection capabilities. Simple predicates like
35/// `Error::is_range` are provided, but the predicates are not exhaustive.
36/// That is, there exist some errors that do not return `true` for any of the
37/// `Error::is_*` predicates.
38///
39/// # Design
40///
41/// This crate follows the "One True God Error Type Pattern," where only one
42/// error type exists for a variety of different operations. This design was
43/// chosen after attempting to provide finer grained error types. But finer
44/// grained error types proved difficult in the face of composition.
45///
46/// More about this design choice can be found in a GitHub issue
47/// [about error types].
48///
49/// [about error types]: https://github.com/BurntSushi/jiff/issues/8
50#[derive(#[automatically_derived]impl ::core::clone::Clone for Error {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        Error { inner: ::core::clone::Clone::clone(&self.inner) }
    }
}Clone)]
51pub struct Error {
52    /// The internal representation of an error.
53    ///
54    /// This is in an `Arc` to make an `Error` cloneable. It could otherwise
55    /// be automatically cloneable, but it embeds a `std::io::Error` when the
56    /// `std` feature is enabled, which isn't cloneable.
57    ///
58    /// This also makes clones cheap. And it also make the size of error equal
59    /// to one word (although a `Box` would achieve that last goal). This is
60    /// why we put the `Arc` here instead of on `std::io::Error` directly.
61    inner: Option<Arc<ErrorInner>>,
62}
63
64#[derive(#[automatically_derived]impl ::core::fmt::Debug for ErrorInner {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field2_finish(f,
            "ErrorInner kind cause", &self.kind, &&self.cause)
    }
}Debug)]
65#[cfg_attr(not(feature = "alloc"), derive(Clone))]
66struct ErrorInner {
67    kind: ErrorKind,
68    #[cfg(feature = "alloc")]
69    cause: Option<Error>,
70}
71
72impl Error {
73    /// Creates a new error value from `core::fmt::Arguments`.
74    ///
75    /// It is expected to use [`format_args!`](format_args) from
76    /// Rust's standard library (available in `core`) to create a
77    /// `core::fmt::Arguments`.
78    ///
79    /// Callers should generally use their own error types. But in some
80    /// circumstances, it can be convenient to manufacture a Jiff error value
81    /// specifically.
82    ///
83    /// # Core-only environments
84    ///
85    /// In core-only environments without a dynamic memory allocator, error
86    /// messages may be degraded in some cases. For example, if the given
87    /// `core::fmt::Arguments` could not be converted to a simple borrowed
88    /// `&str`, then this will ignore the input given and return an "unknown"
89    /// Jiff error.
90    ///
91    /// # Example
92    ///
93    /// ```
94    /// use jiff::Error;
95    ///
96    /// let err = Error::from_args(format_args!("something failed"));
97    /// assert_eq!(err.to_string(), "something failed");
98    /// ```
99    pub fn from_args<'a>(message: core::fmt::Arguments<'a>) -> Error {
100        Error::from(ErrorKind::Adhoc(AdhocError::from_args(message)))
101    }
102
103    /// Returns true when this error originated as a result of a value being
104    /// out of Jiff's supported range.
105    ///
106    /// # Example
107    ///
108    /// ```
109    /// use jiff::civil::Date;
110    ///
111    /// assert!(Date::new(2025, 2, 29).unwrap_err().is_range());
112    /// assert!("2025-02-29".parse::<Date>().unwrap_err().is_range());
113    /// assert!(Date::strptime("%Y-%m-%d", "2025-02-29").unwrap_err().is_range());
114    /// ```
115    pub fn is_range(&self) -> bool {
116        use self::ErrorKind::*;
117        #[allow(non_exhaustive_omitted_patterns)] match *self.root().kind() {
    Bounds(_) | SpecialBounds(_) | JcoreRange(_) => true,
    _ => false,
}matches!(
118            *self.root().kind(),
119            Bounds(_) | SpecialBounds(_) | JcoreRange(_)
120        )
121    }
122
123    /// Returns true when this error originated as a result of an invalid
124    /// configuration of parameters to a function call.
125    ///
126    /// This particular error category is somewhat nebulous, but it's generally
127    /// meant to cover errors that _could_ have been statically prevented by
128    /// Jiff with more types in its API. Instead, a smaller API is preferred.
129    ///
130    /// # Example: invalid rounding options
131    ///
132    /// ```
133    /// use jiff::{SpanRound, ToSpan, Unit};
134    ///
135    /// let span = 44.seconds();
136    /// let err = span.round(
137    ///     SpanRound::new().smallest(Unit::Second).increment(45),
138    /// ).unwrap_err();
139    /// // Rounding increments for seconds must divide evenly into `60`.
140    /// // But `45` does not. Thus, this is a "configuration" error.
141    /// assert!(err.is_invalid_parameter());
142    /// ```
143    ///
144    /// # Example: invalid units
145    ///
146    /// One cannot round a span between dates to units less than days:
147    ///
148    /// ```
149    /// use jiff::{civil::date, Unit};
150    ///
151    /// let date1 = date(2025, 3, 18);
152    /// let date2 = date(2025, 12, 21);
153    /// let err = date1.until((Unit::Hour, date2)).unwrap_err();
154    /// assert!(err.is_invalid_parameter());
155    /// ```
156    ///
157    /// Similarly, one cannot round a span between times to units greater than
158    /// hours:
159    ///
160    /// ```
161    /// use jiff::{civil::time, Unit};
162    ///
163    /// let time1 = time(9, 39, 0, 0);
164    /// let time2 = time(17, 0, 0, 0);
165    /// let err = time1.until((Unit::Day, time2)).unwrap_err();
166    /// assert!(err.is_invalid_parameter());
167    /// ```
168    pub fn is_invalid_parameter(&self) -> bool {
169        use self::ErrorKind::*;
170        use self::civil::Error as CivilError;
171
172        #[allow(non_exhaustive_omitted_patterns)] match *self.root().kind() {
    UnitConfig(_) |
        Civil(CivilError::IllegalTimeWithMicrosecond |
        CivilError::IllegalTimeWithMillisecond |
        CivilError::IllegalTimeWithNanosecond) => true,
    _ => false,
}matches!(
173            *self.root().kind(),
174            UnitConfig(_)
175                | Civil(
176                    CivilError::IllegalTimeWithMicrosecond
177                        | CivilError::IllegalTimeWithMillisecond
178                        | CivilError::IllegalTimeWithNanosecond
179                )
180        )
181    }
182
183    /// Returns true when this error originated as a result of an operation
184    /// failing because an appropriate Jiff crate feature was not enabled.
185    ///
186    /// # Example
187    ///
188    /// ```ignore
189    /// use jiff::tz::TimeZone;
190    ///
191    /// // This passes when the `tz-system` crate feature is NOT enabled.
192    /// assert!(TimeZone::try_system().unwrap_err().is_crate_feature());
193    /// ```
194    pub fn is_crate_feature(&self) -> bool {
195        #[allow(non_exhaustive_omitted_patterns)] match *self.root().kind() {
    ErrorKind::CrateFeature(_) => true,
    _ => false,
}matches!(*self.root().kind(), ErrorKind::CrateFeature(_))
196    }
197
198    /// Returns a reference to this error's corresponding I/O error, if it
199    /// exists.
200    ///
201    /// An I/O error can occur, for example, when opening a time zone database
202    /// via
203    /// [`TimeZoneDatabase::from_dir`](crate::tz::TimeZoneDatabase::from_dir).
204    #[cfg(feature = "std")]
205    pub fn io_error(&self) -> Option<&std::io::Error> {
206        if let ErrorKind::IO(IOError { ref err }) = *self.root().kind() {
207            Some(err)
208        } else {
209            None
210        }
211    }
212}
213
214impl Error {
215    #[inline(never)]
216    #[cold]
217    pub(crate) fn bounds(err: BoundsError) -> Error {
218        Error::from(ErrorKind::Bounds(err))
219    }
220
221    /// Builds a `jiff::Error` from a `jcore::tz::posix::ParseError`.
222    ///
223    /// This very much cannot be added as a `From` impl because that would
224    /// introduce a public dependency on `jcore`.
225    #[inline(never)]
226    #[cold]
227    pub(crate) fn jcore_posix_parse(
228        err: jcore::tz::posix::ParseError,
229    ) -> Error {
230        Error::from(ErrorKind::JcorePosixParse(err))
231    }
232
233    /// Builds a `jiff::Error` from a `jcore::tz::tzif::ParseError`.
234    ///
235    /// This very much cannot be added as a `From` impl because that would
236    /// introduce a public dependency on `jcore`.
237    #[cfg(feature = "alloc")]
238    #[inline(never)]
239    #[cold]
240    pub(crate) fn jcore_tzif_parse(err: jcore::tz::tzif::ParseError) -> Error {
241        Error::from(ErrorKind::JcoreTzifParse(err))
242    }
243
244    /// Builds a `jiff::Error` from a `jcore::bounds::RangeError`.
245    ///
246    /// This very much cannot be added as a `From` impl because that would
247    /// introduce a public dependency on `jcore`.
248    #[inline(never)]
249    #[cold]
250    pub(crate) fn jcore_range(err: jcore::bounds::RangeError) -> Error {
251        Error::from(ErrorKind::JcoreRange(err))
252    }
253
254    #[inline(never)]
255    #[cold]
256    pub(crate) fn special_bounds(err: SpecialBoundsError) -> Error {
257        Error::from(ErrorKind::SpecialBounds(err))
258    }
259
260    /// A convenience constructor for building an I/O error.
261    ///
262    /// This returns an error that is just a simple wrapper around the
263    /// `std::io::Error` type. In general, callers should always attach some
264    /// kind of context to this error (like a file path).
265    ///
266    /// This is only available when the `std` feature is enabled.
267    #[cfg(feature = "std")]
268    #[inline(never)]
269    #[cold]
270    pub(crate) fn io(err: std::io::Error) -> Error {
271        Error::from(ErrorKind::IO(IOError { err }))
272    }
273
274    /// Contextualizes this error by associating the given file path with it.
275    ///
276    /// This is a convenience routine for calling `Error::context` with a
277    /// `FilePathError`.
278    #[cfg(any(feature = "tzdb-zoneinfo", feature = "tzdb-concatenated"))]
279    #[inline(never)]
280    #[cold]
281    pub(crate) fn path(self, path: impl Into<std::path::PathBuf>) -> Error {
282        let err = Error::from(ErrorKind::FilePath(FilePathError {
283            path: path.into(),
284        }));
285        self.context(err)
286    }
287
288    /*
289    /// Creates a new "unknown" Jiff error.
290    ///
291    /// The benefit of this API is that it permits creating an `Error` in a
292    /// `const` context. But the error message quality is currently pretty
293    /// bad: it's just a generic "unknown Jiff error" message.
294    ///
295    /// This could be improved to take a `&'static str`, but I believe this
296    /// will require pointer tagging in order to avoid increasing the size of
297    /// `Error`. (Which is important, because of how many perf sensitive
298    /// APIs return a `Result<T, Error>` in Jiff.
299    pub(crate) const fn unknown() -> Error {
300        Error { inner: None }
301    }
302    */
303
304    #[cfg_attr(feature = "perf-inline", inline(always))]
305    pub(crate) fn context(self, consequent: impl IntoError) -> Error {
306        self.context_impl(consequent.into_error())
307    }
308
309    #[inline(never)]
310    #[cold]
311    fn context_impl(self, _consequent: Error) -> Error {
312        #[cfg(feature = "alloc")]
313        {
314            let mut err = _consequent;
315            if err.inner.is_none() {
316                err = Error::from(ErrorKind::Unknown);
317            }
318            let inner = err.inner.as_mut().unwrap();
319            if !inner.cause.is_none() {
    {
        ::core::panicking::panic_fmt(format_args!("cause of consequence must be `None`"));
    }
};assert!(
320                inner.cause.is_none(),
321                "cause of consequence must be `None`"
322            );
323            // OK because we just created this error so the Arc
324            // has one reference.
325            Arc::get_mut(inner).unwrap().cause = Some(self);
326            err
327        }
328        #[cfg(not(feature = "alloc"))]
329        {
330            // We just completely drop `self`. :-(
331            //
332            // 2025-12-21: ... actually, we used to drop self, but this
333            // ends up dropping the root cause. And the root cause
334            // is how the predicates on `Error` work. So we drop the
335            // consequent instead.
336            self
337        }
338    }
339
340    /// Returns the root error in this chain.
341    fn root(&self) -> &Error {
342        // OK because `Error::chain` is guaranteed to return a non-empty
343        // iterator.
344        self.chain().last().unwrap()
345    }
346
347    /// Returns a chain of error values.
348    ///
349    /// This starts with the most recent error added to the chain. That is,
350    /// the highest level context. The last error in the chain is always the
351    /// "root" cause. That is, the error closest to the point where something
352    /// has gone wrong.
353    ///
354    /// The iterator returned is guaranteed to yield at least one error.
355    fn chain(&self) -> impl Iterator<Item = &Error> {
356        #[cfg(feature = "alloc")]
357        {
358            let mut err = self;
359            core::iter::once(err).chain(core::iter::from_fn(move || {
360                err = err
361                    .inner
362                    .as_ref()
363                    .and_then(|inner| inner.cause.as_ref())?;
364                Some(err)
365            }))
366        }
367        #[cfg(not(feature = "alloc"))]
368        {
369            core::iter::once(self)
370        }
371    }
372
373    /// Returns a reference to the kind of this error.
374    fn kind(&self) -> &ErrorKind {
375        self.inner
376            .as_ref()
377            .map(|inner| &inner.kind)
378            .unwrap_or(&ErrorKind::Unknown)
379    }
380}
381
382impl core::error::Error for Error {}
383
384impl core::fmt::Display for Error {
385    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
386        let mut it = self.chain().peekable();
387        while let Some(err) = it.next() {
388            core::fmt::Display::fmt(err.kind(), f)?;
389            if it.peek().is_some() {
390                f.write_str(": ")?;
391            }
392        }
393        Ok(())
394    }
395}
396
397impl core::fmt::Debug for Error {
398    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
399        if !f.alternate() {
400            core::fmt::Display::fmt(self, f)
401        } else {
402            let Some(ref inner) = self.inner else {
403                return f
404                    .debug_struct("Error")
405                    .field("kind", &"None")
406                    .finish();
407            };
408            #[cfg(feature = "alloc")]
409            {
410                f.debug_struct("Error")
411                    .field("kind", &inner.kind)
412                    .field("cause", &inner.cause)
413                    .finish()
414            }
415            #[cfg(not(feature = "alloc"))]
416            {
417                f.debug_struct("Error").field("kind", &inner.kind).finish()
418            }
419        }
420    }
421}
422
423#[cfg(feature = "defmt")]
424impl defmt::Format for Error {
425    fn format(&self, f: defmt::Formatter) {
426        let Some(ref inner) = self.inner else {
427            return defmt::write!(f, "Error {{ kind: None }}");
428        };
429        #[cfg(feature = "alloc")]
430        {
431            defmt::write!(
432                f,
433                "Error {{ kind: {}, cause: {} }}",
434                inner.kind,
435                inner.cause
436            );
437        }
438        #[cfg(not(feature = "alloc"))]
439        {
440            defmt::write!(f, "Error {{ kind: {} }}", inner.kind);
441        }
442    }
443}
444
445/// The underlying kind of a [`Error`].
446#[derive(#[automatically_derived]impl ::core::fmt::Debug for ErrorKind {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Self::Adhoc(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Adhoc",
                    &__self_0),
            Self::Bounds(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Bounds", &__self_0),
            Self::Civil(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Civil",
                    &__self_0),
            Self::CrateFeature(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "CrateFeature", &__self_0),
            Self::Duration(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Duration", &__self_0),
            Self::FilePath(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "FilePath", &__self_0),
            Self::Fmt(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Fmt",
                    &__self_0),
            Self::FmtFriendly(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "FmtFriendly", &__self_0),
            Self::FmtOffset(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "FmtOffset", &__self_0),
            Self::FmtRfc2822(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "FmtRfc2822", &__self_0),
            Self::FmtRfc9557(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "FmtRfc9557", &__self_0),
            Self::FmtTemporal(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "FmtTemporal", &__self_0),
            Self::FmtUtil(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "FmtUtil", &__self_0),
            Self::FmtStrtime(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "FmtStrtime", &__self_0),
            Self::FmtStrtimeFormat(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "FmtStrtimeFormat", &__self_0),
            Self::FmtStrtimeParse(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "FmtStrtimeParse", &__self_0),
            Self::IO(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "IO",
                    &__self_0),
            Self::JcorePosixParse(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "JcorePosixParse", &__self_0),
            Self::JcoreTzifParse(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "JcoreTzifParse", &__self_0),
            Self::JcoreRange(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "JcoreRange", &__self_0),
            Self::OsStrUtf8(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "OsStrUtf8", &__self_0),
            Self::ParseInt(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ParseInt", &__self_0),
            Self::ParseFraction(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ParseFraction", &__self_0),
            Self::RoundingIncrement(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "RoundingIncrement", &__self_0),
            Self::SignedDuration(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "SignedDuration", &__self_0),
            Self::Span(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "Span",
                    &__self_0),
            Self::UnitConfig(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "UnitConfig", &__self_0),
            Self::SpecialBounds(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "SpecialBounds", &__self_0),
            Self::Timestamp(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "Timestamp", &__self_0),
            Self::TzAmbiguous(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TzAmbiguous", &__self_0),
            Self::TzDb(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "TzDb",
                    &__self_0),
            Self::TzConcatenated(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TzConcatenated", &__self_0),
            Self::TzOffset(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TzOffset", &__self_0),
            Self::TzSystem(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TzSystem", &__self_0),
            Self::TzTimeZone(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "TzTimeZone", &__self_0),
            Self::TzZic(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f, "TzZic",
                    &__self_0),
            Self::Unknown => ::core::fmt::Formatter::write_str(f, "Unknown"),
            Self::ZonedDateTime(__self_0) =>
                ::core::fmt::Formatter::debug_struct_field1_finish(f,
                    "ZonedDateTime", &__self_0),
        }
    }
}Debug)]
447#[cfg_attr(not(feature = "alloc"), derive(Clone))]
448#[cfg_attr(feature = "defmt", derive(defmt::Format))]
449enum ErrorKind {
450    Adhoc(AdhocError),
451    Bounds(BoundsError),
452    Civil(self::civil::Error),
453    CrateFeature(CrateFeatureError),
454    Duration(self::duration::Error),
455    #[allow(dead_code)] // not used in some feature configs
456    FilePath(FilePathError),
457    Fmt(self::fmt::Error),
458    FmtFriendly(self::fmt::friendly::Error),
459    FmtOffset(self::fmt::offset::Error),
460    FmtRfc2822(self::fmt::rfc2822::Error),
461    FmtRfc9557(self::fmt::rfc9557::Error),
462    FmtTemporal(self::fmt::temporal::Error),
463    FmtUtil(self::fmt::util::Error),
464    FmtStrtime(self::fmt::strtime::Error),
465    FmtStrtimeFormat(self::fmt::strtime::FormatError),
466    FmtStrtimeParse(self::fmt::strtime::ParseError),
467    #[allow(dead_code)] // not used in some feature configs
468    IO(IOError),
469    JcorePosixParse(jcore::tz::posix::ParseError),
470    #[cfg(feature = "alloc")]
471    JcoreTzifParse(jcore::tz::tzif::ParseError),
472    JcoreRange(jcore::bounds::RangeError),
473    OsStrUtf8(self::util::OsStrUtf8Error),
474    ParseInt(self::util::ParseIntError),
475    ParseFraction(self::util::ParseFractionError),
476    RoundingIncrement(self::util::RoundingIncrementError),
477    SignedDuration(self::signed_duration::Error),
478    Span(self::span::Error),
479    UnitConfig(self::unit::UnitConfigError),
480    SpecialBounds(SpecialBoundsError),
481    Timestamp(self::timestamp::Error),
482    TzAmbiguous(self::tz::ambiguous::Error),
483    TzDb(self::tz::db::Error),
484    TzConcatenated(self::tz::concatenated::Error),
485    TzOffset(self::tz::offset::Error),
486    TzSystem(self::tz::system::Error),
487    TzTimeZone(self::tz::timezone::Error),
488    #[allow(dead_code)]
489    TzZic(self::tz::zic::Error),
490    Unknown,
491    ZonedDateTime(self::zoned::Error),
492}
493
494impl core::fmt::Display for ErrorKind {
495    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
496        use self::ErrorKind::*;
497
498        match *self {
499            Adhoc(ref msg) => msg.fmt(f),
500            Bounds(ref msg) => msg.fmt(f),
501            JcorePosixParse(ref msg) => msg.fmt(f),
502            #[cfg(feature = "alloc")]
503            JcoreTzifParse(ref msg) => msg.fmt(f),
504            JcoreRange(ref msg) => msg.fmt(f),
505            Civil(ref err) => err.fmt(f),
506            CrateFeature(ref err) => err.fmt(f),
507            Duration(ref err) => err.fmt(f),
508            FilePath(ref err) => err.fmt(f),
509            Fmt(ref err) => err.fmt(f),
510            FmtFriendly(ref err) => err.fmt(f),
511            FmtOffset(ref err) => err.fmt(f),
512            FmtRfc2822(ref err) => err.fmt(f),
513            FmtRfc9557(ref err) => err.fmt(f),
514            FmtUtil(ref err) => err.fmt(f),
515            FmtStrtime(ref err) => err.fmt(f),
516            FmtStrtimeFormat(ref err) => err.fmt(f),
517            FmtStrtimeParse(ref err) => err.fmt(f),
518            FmtTemporal(ref err) => err.fmt(f),
519            IO(ref err) => err.fmt(f),
520            OsStrUtf8(ref err) => err.fmt(f),
521            ParseInt(ref err) => err.fmt(f),
522            ParseFraction(ref err) => err.fmt(f),
523            RoundingIncrement(ref err) => err.fmt(f),
524            SignedDuration(ref err) => err.fmt(f),
525            Span(ref err) => err.fmt(f),
526            UnitConfig(ref err) => err.fmt(f),
527            SpecialBounds(ref msg) => msg.fmt(f),
528            Timestamp(ref err) => err.fmt(f),
529            TzAmbiguous(ref err) => err.fmt(f),
530            TzDb(ref err) => err.fmt(f),
531            TzConcatenated(ref err) => err.fmt(f),
532            TzOffset(ref err) => err.fmt(f),
533            TzSystem(ref err) => err.fmt(f),
534            TzTimeZone(ref err) => err.fmt(f),
535            TzZic(ref err) => err.fmt(f),
536            Unknown => f.write_str("unknown Jiff error"),
537            ZonedDateTime(ref err) => err.fmt(f),
538        }
539    }
540}
541
542impl From<ErrorKind> for Error {
543    fn from(kind: ErrorKind) -> Error {
544        #[cfg(feature = "alloc")]
545        {
546            Error { inner: Some(Arc::new(ErrorInner { kind, cause: None })) }
547        }
548        #[cfg(not(feature = "alloc"))]
549        {
550            Error { inner: Some(Arc::new(ErrorInner { kind })) }
551        }
552    }
553}
554
555/// A generic error message.
556///
557/// This used to be used to represent most errors in Jiff. But then I switched
558/// to more structured error types (internally). We still keep this around to
559/// support the `Error::from_args` public API, which permits users of Jiff to
560/// manifest their own `Error` values from an arbitrary message.
561#[cfg_attr(not(feature = "alloc"), derive(Clone))]
562#[cfg_attr(feature = "defmt", derive(defmt::Format))]
563struct AdhocError {
564    #[cfg(feature = "alloc")]
565    #[cfg_attr(feature = "defmt", defmt(Debug2Format))]
566    message: alloc::boxed::Box<str>,
567    #[cfg(not(feature = "alloc"))]
568    message: &'static str,
569}
570
571impl AdhocError {
572    fn from_args<'a>(message: core::fmt::Arguments<'a>) -> AdhocError {
573        #[cfg(feature = "alloc")]
574        {
575            use alloc::string::ToString;
576
577            let message = message.to_string().into_boxed_str();
578            AdhocError { message }
579        }
580        #[cfg(not(feature = "alloc"))]
581        {
582            let message = message.as_str().unwrap_or(
583                "unknown Jiff error (better error messages require \
584                 enabling the `alloc` feature for the `jiff` crate)",
585            );
586            AdhocError { message }
587        }
588    }
589}
590
591impl core::error::Error for AdhocError {}
592
593impl core::fmt::Display for AdhocError {
594    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
595        core::fmt::Display::fmt(&self.message, f)
596    }
597}
598
599impl core::fmt::Debug for AdhocError {
600    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
601        core::fmt::Debug::fmt(&self.message, f)
602    }
603}
604
605/// An error used whenever a failure is caused by a missing crate feature.
606///
607/// This enum doesn't necessarily contain every Jiff crate feature. It only
608/// contains the features whose absence can result in an error.
609#[derive(#[automatically_derived]impl ::core::clone::Clone for CrateFeatureError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn clone(&self) -> Self {
        match self {
            Self::TzSystem => CrateFeatureError::TzSystem,
            Self::TzdbConcatenated => CrateFeatureError::TzdbConcatenated,
            Self::TzdbZoneInfo => CrateFeatureError::TzdbZoneInfo,
        }
    }
}Clone, #[automatically_derived]impl ::core::fmt::Debug for CrateFeatureError {
    #[inline]
    #[rustc_trivial_field_reads]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::write_str(f,
            match self {
                CrateFeatureError::TzSystem => "TzSystem",
                CrateFeatureError::TzdbConcatenated => "TzdbConcatenated",
                CrateFeatureError::TzdbZoneInfo => "TzdbZoneInfo",
            })
    }
}Debug)]
610#[cfg_attr(feature = "defmt", derive(defmt::Format))]
611pub(crate) enum CrateFeatureError {
612    #[cfg(not(feature = "tz-system"))]
613    TzSystem,
614    #[cfg(not(feature = "tzdb-concatenated"))]
615    TzdbConcatenated,
616    #[cfg(not(feature = "tzdb-zoneinfo"))]
617    TzdbZoneInfo,
618}
619
620impl From<CrateFeatureError> for Error {
621    #[cold]
622    #[inline(never)]
623    fn from(err: CrateFeatureError) -> Error {
624        ErrorKind::CrateFeature(err).into()
625    }
626}
627
628impl core::fmt::Display for CrateFeatureError {
629    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
630        #[allow(unused_imports)]
631        use self::CrateFeatureError::*;
632
633        f.write_str("operation failed because Jiff crate feature `")?;
634        #[allow(unused_variables)]
635        let name: &str = match *self {
636            #[cfg(not(feature = "tz-system"))]
637            TzSystem => "tz-system",
638            #[cfg(not(feature = "tzdb-concatenated"))]
639            TzdbConcatenated => "tzdb-concatenated",
640            #[cfg(not(feature = "tzdb-zoneinfo"))]
641            TzdbZoneInfo => "tzdb-zoneinfo",
642        };
643        #[allow(unreachable_code)]
644        {
645            core::fmt::Display::fmt(name, f)?;
646            f.write_str("` is not enabled")
647        }
648    }
649}
650
651/// A `std::io::Error`.
652///
653/// This type is itself always available, even when the `std` feature is not
654/// enabled. When `std` is not enabled, a value of this type can never be
655/// constructed.
656///
657/// Otherwise, this type is a simple wrapper around `std::io::Error`. Its
658/// purpose is to encapsulate the conditional compilation based on the `std`
659/// feature.
660#[cfg_attr(not(feature = "alloc"), derive(Clone))]
661struct IOError {
662    #[cfg(feature = "std")]
663    err: std::io::Error,
664}
665
666impl core::error::Error for IOError {}
667
668impl core::fmt::Display for IOError {
669    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
670        #[cfg(feature = "std")]
671        {
672            self.err.fmt(f)
673        }
674        #[cfg(not(feature = "std"))]
675        {
676            f.write_str("<BUG: SHOULD NOT EXIST>")
677        }
678    }
679}
680
681impl core::fmt::Debug for IOError {
682    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
683        #[cfg(feature = "std")]
684        {
685            f.debug_struct("IOError").field("err", &self.err).finish()
686        }
687        #[cfg(not(feature = "std"))]
688        {
689            f.write_str("<BUG: SHOULD NOT EXIST>")
690        }
691    }
692}
693
694#[cfg(feature = "defmt")]
695impl defmt::Format for IOError {
696    fn format(&self, f: defmt::Formatter) {
697        // `std::io::Error` does not implement `defmt::Format`. Since this
698        // error is std-only and defmt is mainly used in embedded contexts,
699        // omitting the error is probably fine.
700        defmt::write!(f, "IOError(unavailable)");
701    }
702}
703
704#[cfg(feature = "std")]
705impl From<std::io::Error> for IOError {
706    fn from(err: std::io::Error) -> IOError {
707        IOError { err }
708    }
709}
710
711#[cfg_attr(not(feature = "alloc"), derive(Clone))]
712struct FilePathError {
713    #[cfg(feature = "std")]
714    path: std::path::PathBuf,
715}
716
717impl core::error::Error for FilePathError {}
718
719impl core::fmt::Display for FilePathError {
720    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
721        #[cfg(feature = "std")]
722        {
723            self.path.display().fmt(f)
724        }
725        #[cfg(not(feature = "std"))]
726        {
727            f.write_str("<BUG: SHOULD NOT EXIST>")
728        }
729    }
730}
731
732impl core::fmt::Debug for FilePathError {
733    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
734        #[cfg(feature = "std")]
735        {
736            f.debug_struct("FilePathError").field("path", &self.path).finish()
737        }
738        #[cfg(not(feature = "std"))]
739        {
740            f.write_str("<BUG: SHOULD NOT EXIST>")
741        }
742    }
743}
744
745#[cfg(feature = "defmt")]
746impl defmt::Format for FilePathError {
747    fn format(&self, f: defmt::Formatter) {
748        // `std::path::PathBuf` does not implement `defmt::Format`. Since this
749        // error is std-only and defmt is mainly used in embedded contexts,
750        // omitting the path is probably fine.
751        defmt::write!(f, "FilePathError(unavailable)");
752    }
753}
754
755/// A simple trait to encapsulate automatic conversion to `Error`.
756///
757/// This trait basically exists to make `Error::context` work without needing
758/// to rely on public `From` impls. For example, without this trait, we might
759/// otherwise write `impl From<String> for Error`. But this would make it part
760/// of the public API. Which... maybe we should do, but at time of writing,
761/// I'm starting very conservative so that we can evolve errors in semver
762/// compatible ways.
763pub(crate) trait IntoError {
764    fn into_error(self) -> Error;
765}
766
767impl IntoError for Error {
768    #[inline(always)]
769    fn into_error(self) -> Error {
770        self
771    }
772}
773
774// This trait impl is okay because `IntoError` is a crate-internal trait. So
775// this impl will not cause a public dependency on `jcore`.
776impl IntoError for jcore::bounds::RangeError {
777    #[inline(always)]
778    fn into_error(self) -> Error {
779        Error::jcore_range(self)
780    }
781}
782
783/// A trait for contextualizing error values.
784///
785/// This makes it easy to contextualize either `Error` or `Result<T, Error>`.
786/// Specifically, in the latter case, it absolves one of the need to call
787/// `map_err` everywhere one wants to add context to an error.
788///
789/// This trick was borrowed from `anyhow`.
790pub(crate) trait ErrorContext<T, E> {
791    /// Contextualize the given consequent error with this (`self`) error as
792    /// the cause.
793    ///
794    /// This is equivalent to saying that "consequent is caused by self."
795    ///
796    /// Note that if an `Error` is given for `kind`, then this panics if it has
797    /// a cause. (Because the cause would otherwise be dropped. An error causal
798    /// chain is just a linked list, not a tree.)
799    fn context(self, consequent: impl IntoError) -> Result<T, Error>;
800
801    /// Like `context`, but hides error construction within a closure.
802    ///
803    /// This is useful if the creation of the consequent error is not otherwise
804    /// guarded and when error construction is potentially "costly" (i.e., it
805    /// allocates). The closure avoids paying the cost of contextual error
806    /// creation in the happy path.
807    ///
808    /// Usually this only makes sense to use on a `Result<T, Error>`, otherwise
809    /// the closure is just executed immediately anyway.
810    fn with_context<C: IntoError>(
811        self,
812        consequent: impl FnOnce() -> C,
813    ) -> Result<T, Error>;
814}
815
816impl<T, E> ErrorContext<T, E> for Result<T, E>
817where
818    E: IntoError,
819{
820    #[cfg_attr(feature = "perf-inline", inline(always))]
821    fn context(self, consequent: impl IntoError) -> Result<T, Error> {
822        self.map_err(|err| {
823            err.into_error().context_impl(consequent.into_error())
824        })
825    }
826
827    #[cfg_attr(feature = "perf-inline", inline(always))]
828    fn with_context<C: IntoError>(
829        self,
830        consequent: impl FnOnce() -> C,
831    ) -> Result<T, Error> {
832        self.map_err(|err| {
833            err.into_error().context_impl(consequent().into_error())
834        })
835    }
836}
837
838#[cfg(test)]
839mod tests {
840    use super::*;
841
842    // We test that our 'Error' type is the size we expect. This isn't an API
843    // guarantee, but if the size increases, we really want to make sure we
844    // decide to do that intentionally. So this should be a speed bump. And in
845    // general, we should not increase the size without a very good reason.
846    #[test]
847    fn error_size() {
848        if cfg!(feature = "alloc") {
849            let expected_size = core::mem::size_of::<usize>();
850            assert_eq!(expected_size, core::mem::size_of::<Error>());
851            return;
852        }
853        // oooowwwwwwwwwwwch.
854        //
855        // Like, this is horrible, right? core-only environments are
856        // precisely the place where one want to keep things slim. But
857        // in core-only, I don't know of a way to introduce any sort of
858        // indirection in the library level without using a completely
859        // different API.
860        //
861        // This is what makes me doubt that core-only Jiff is actually
862        // useful. In what context are people using a huge library like
863        // Jiff but can't define a small little heap allocator?
864        //
865        // OK, this used to be `expected_size *= 10`, but I slimmed it down
866        // to x3. Still kinda sucks right? If we tried harder, I think we
867        // could probably slim this down more. And if we were willing to
868        // sacrifice error message quality even more (like, all the way),
869        // then we could make `Error` a zero sized type. Which might
870        // actually be the right trade-off for core-only, but I'll hold off
871        // until we have some real world use cases.
872        //
873        // OK... after switching to structured errors, this jumped
874        // back up to `expected_size *= 6`. And that was with me being
875        // conscientious about what data we store inside of error types.
876        // Blech.
877        //
878        // 2026-01-14: A change to the `Offset` type made this move back
879        // down to `expected_size *= 4`.
880        //
881        // 2026-05-28: No changes here, but `4 * pointer-size` is not the
882        // right calculation here. This is unfortunately coupled with an
883        // internal representation for the biggest possible error variant.
884        // And also compiler optimizations. But at time of writing, it's
885        // from the `jiff::error::tz::offset::Error` enum. We get 4 32-bit
886        // integers (always 32-bit) plus one pointer sized discriminant.
887        //
888        // 2026-05-28 redux: this now seems coupled with compiler
889        // optimizations. So just give up and check that it's reasonable.
890        let got = core::mem::size_of::<Error>();
891        assert!(got <= 40, "wanted error size to be <= 40, but got {got}");
892    }
893}