1use crate::util::{
2 b::{BoundsError, SpecialBoundsError},
3sync::Arc,
4};
56pub(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;
1617/// 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.
61inner: Option<Arc<ErrorInner>>,
62}
6364#[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")]
69cause: Option<Error>,
70}
7172impl 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 /// ```
99pub fn from_args<'a>(message: core::fmt::Arguments<'a>) -> Error {
100Error::from(ErrorKind::Adhoc(AdhocError::from_args(message)))
101 }
102103/// 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 /// ```
115pub fn is_range(&self) -> bool {
116use 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 }
122123/// 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 /// ```
168pub fn is_invalid_parameter(&self) -> bool {
169use self::ErrorKind::*;
170use self::civil::Erroras CivilError;
171172#[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 }
182183/// 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 /// ```
194pub 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 }
197198/// 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")]
205pub fn io_error(&self) -> Option<&std::io::Error> {
206if let ErrorKind::IO(IOError { ref err }) = *self.root().kind() {
207Some(err)
208 } else {
209None210 }
211 }
212}
213214impl Error {
215#[inline(never)]
216 #[cold]
217pub(crate) fn bounds(err: BoundsError) -> Error {
218Error::from(ErrorKind::Bounds(err))
219 }
220221/// 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]
227pub(crate) fn jcore_posix_parse(
228 err: jcore::tz::posix::ParseError,
229 ) -> Error {
230Error::from(ErrorKind::JcorePosixParse(err))
231 }
232233/// 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]
240pub(crate) fn jcore_tzif_parse(err: jcore::tz::tzif::ParseError) -> Error {
241Error::from(ErrorKind::JcoreTzifParse(err))
242 }
243244/// 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]
250pub(crate) fn jcore_range(err: jcore::bounds::RangeError) -> Error {
251Error::from(ErrorKind::JcoreRange(err))
252 }
253254#[inline(never)]
255 #[cold]
256pub(crate) fn special_bounds(err: SpecialBoundsError) -> Error {
257Error::from(ErrorKind::SpecialBounds(err))
258 }
259260/// 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]
270pub(crate) fn io(err: std::io::Error) -> Error {
271Error::from(ErrorKind::IO(IOError { err }))
272 }
273274/// 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]
281pub(crate) fn path(self, path: impl Into<std::path::PathBuf>) -> Error {
282let err = Error::from(ErrorKind::FilePath(FilePathError {
283 path: path.into(),
284 }));
285self.context(err)
286 }
287288/*
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 */
303304#[cfg_attr(feature = "perf-inline", inline(always))]
305pub(crate) fn context(self, consequent: impl IntoError) -> Error {
306self.context_impl(consequent.into_error())
307 }
308309#[inline(never)]
310 #[cold]
311fn context_impl(self, _consequent: Error) -> Error {
312#[cfg(feature = "alloc")]
313{
314let mut err = _consequent;
315if err.inner.is_none() {
316err = Error::from(ErrorKind::Unknown);
317 }
318let inner = err.inner.as_mut().unwrap();
319if !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.
325Arc::get_mut(inner).unwrap().cause = Some(self);
326err327 }
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.
336self
337}
338 }
339340/// Returns the root error in this chain.
341fn root(&self) -> &Error {
342// OK because `Error::chain` is guaranteed to return a non-empty
343 // iterator.
344self.chain().last().unwrap()
345 }
346347/// 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.
355fn chain(&self) -> impl Iterator<Item = &Error> {
356#[cfg(feature = "alloc")]
357{
358let mut err = self;
359 core::iter::once(err).chain(core::iter::from_fn(move || {
360err = err
361 .inner
362 .as_ref()
363 .and_then(|inner| inner.cause.as_ref())?;
364Some(err)
365 }))
366 }
367#[cfg(not(feature = "alloc"))]
368{
369 core::iter::once(self)
370 }
371 }
372373/// Returns a reference to the kind of this error.
374fn kind(&self) -> &ErrorKind {
375self.inner
376 .as_ref()
377 .map(|inner| &inner.kind)
378 .unwrap_or(&ErrorKind::Unknown)
379 }
380}
381382impl core::error::Errorfor Error {}
383384impl core::fmt::Displayfor Error {
385fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
386let mut it = self.chain().peekable();
387while let Some(err) = it.next() {
388 core::fmt::Display::fmt(err.kind(), f)?;
389if it.peek().is_some() {
390 f.write_str(": ")?;
391 }
392 }
393Ok(())
394 }
395}
396397impl core::fmt::Debugfor Error {
398fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
399if !f.alternate() {
400 core::fmt::Display::fmt(self, f)
401 } else {
402let Some(ref inner) = self.inner else {
403return f404 .debug_struct("Error")
405 .field("kind", &"None")
406 .finish();
407 };
408#[cfg(feature = "alloc")]
409{
410f.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}
422423#[cfg(feature = "defmt")]
424impl defmt::Format for Error {
425fn format(&self, f: defmt::Formatter) {
426let Some(ref inner) = self.inner else {
427return defmt::write!(f, "Error {{ kind: None }}");
428 };
429#[cfg(feature = "alloc")]
430{
431defmt::write!(
432 f,
433"Error {{ kind: {}, cause: {} }}",
434 inner.kind,
435 inner.cause
436 );
437 }
438#[cfg(not(feature = "alloc"))]
439{
440defmt::write!(f, "Error {{ kind: {} }}", inner.kind);
441 }
442 }
443}
444445/// 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
456FilePath(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
468IO(IOError),
469 JcorePosixParse(jcore::tz::posix::ParseError),
470#[cfg(feature = "alloc")]
471JcoreTzifParse(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)]
489TzZic(self::tz::zic::Error),
490 Unknown,
491 ZonedDateTime(self::zoned::Error),
492}
493494impl core::fmt::Displayfor ErrorKind {
495fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
496use self::ErrorKind::*;
497498match *self {
499Adhoc(ref msg) => msg.fmt(f),
500Bounds(ref msg) => msg.fmt(f),
501JcorePosixParse(ref msg) => msg.fmt(f),
502#[cfg(feature = "alloc")]
503JcoreTzifParse(ref msg) => msg.fmt(f),
504JcoreRange(ref msg) => msg.fmt(f),
505Civil(ref err) => err.fmt(f),
506CrateFeature(ref err) => err.fmt(f),
507Duration(ref err) => err.fmt(f),
508FilePath(ref err) => err.fmt(f),
509Fmt(ref err) => err.fmt(f),
510FmtFriendly(ref err) => err.fmt(f),
511FmtOffset(ref err) => err.fmt(f),
512FmtRfc2822(ref err) => err.fmt(f),
513FmtRfc9557(ref err) => err.fmt(f),
514FmtUtil(ref err) => err.fmt(f),
515FmtStrtime(ref err) => err.fmt(f),
516FmtStrtimeFormat(ref err) => err.fmt(f),
517FmtStrtimeParse(ref err) => err.fmt(f),
518FmtTemporal(ref err) => err.fmt(f),
519IO(ref err) => err.fmt(f),
520OsStrUtf8(ref err) => err.fmt(f),
521ParseInt(ref err) => err.fmt(f),
522ParseFraction(ref err) => err.fmt(f),
523RoundingIncrement(ref err) => err.fmt(f),
524SignedDuration(ref err) => err.fmt(f),
525Span(ref err) => err.fmt(f),
526UnitConfig(ref err) => err.fmt(f),
527SpecialBounds(ref msg) => msg.fmt(f),
528Timestamp(ref err) => err.fmt(f),
529TzAmbiguous(ref err) => err.fmt(f),
530TzDb(ref err) => err.fmt(f),
531TzConcatenated(ref err) => err.fmt(f),
532TzOffset(ref err) => err.fmt(f),
533TzSystem(ref err) => err.fmt(f),
534TzTimeZone(ref err) => err.fmt(f),
535TzZic(ref err) => err.fmt(f),
536Unknown => f.write_str("unknown Jiff error"),
537ZonedDateTime(ref err) => err.fmt(f),
538 }
539 }
540}
541542impl From<ErrorKind> for Error {
543fn from(kind: ErrorKind) -> Error {
544#[cfg(feature = "alloc")]
545{
546Error { 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}
554555/// 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))]
566message: alloc::boxed::Box<str>,
567#[cfg(not(feature = "alloc"))]
568message: &'static str,
569}
570571impl AdhocError {
572fn from_args<'a>(message: core::fmt::Arguments<'a>) -> AdhocError {
573#[cfg(feature = "alloc")]
574{
575use alloc::string::ToString;
576577let message = message.to_string().into_boxed_str();
578AdhocError { message }
579 }
580#[cfg(not(feature = "alloc"))]
581{
582let 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}
590591impl core::error::Errorfor AdhocError {}
592593impl core::fmt::Displayfor AdhocError {
594fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
595 core::fmt::Display::fmt(&self.message, f)
596 }
597}
598599impl core::fmt::Debugfor AdhocError {
600fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
601 core::fmt::Debug::fmt(&self.message, f)
602 }
603}
604605/// 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"))]
613TzSystem,
614#[cfg(not(feature = "tzdb-concatenated"))]
615TzdbConcatenated,
616#[cfg(not(feature = "tzdb-zoneinfo"))]
617TzdbZoneInfo,
618}
619620impl From<CrateFeatureError> for Error {
621#[cold]
622 #[inline(never)]
623fn from(err: CrateFeatureError) -> Error {
624 ErrorKind::CrateFeature(err).into()
625 }
626}
627628impl core::fmt::Displayfor CrateFeatureError {
629fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
630#[allow(unused_imports)]
631use self::CrateFeatureError::*;
632633 f.write_str("operation failed because Jiff crate feature `")?;
634#[allow(unused_variables)]
635let name: &str = match *self {
636#[cfg(not(feature = "tz-system"))]
637TzSystem => "tz-system",
638#[cfg(not(feature = "tzdb-concatenated"))]
639TzdbConcatenated => "tzdb-concatenated",
640#[cfg(not(feature = "tzdb-zoneinfo"))]
641TzdbZoneInfo => "tzdb-zoneinfo",
642 };
643#[allow(unreachable_code)]
644{
645 core::fmt::Display::fmt(name, f)?;
646f.write_str("` is not enabled")
647 }
648 }
649}
650651/// 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")]
663err: std::io::Error,
664}
665666impl core::error::Errorfor IOError {}
667668impl core::fmt::Displayfor IOError {
669fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
670#[cfg(feature = "std")]
671{
672self.err.fmt(f)
673 }
674#[cfg(not(feature = "std"))]
675{
676 f.write_str("<BUG: SHOULD NOT EXIST>")
677 }
678 }
679}
680681impl core::fmt::Debugfor IOError {
682fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
683#[cfg(feature = "std")]
684{
685f.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}
693694#[cfg(feature = "defmt")]
695impl defmt::Format for IOError {
696fn 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.
700defmt::write!(f, "IOError(unavailable)");
701 }
702}
703704#[cfg(feature = "std")]
705impl From<std::io::Error> for IOError {
706fn from(err: std::io::Error) -> IOError {
707IOError { err }
708 }
709}
710711#[cfg_attr(not(feature = "alloc"), derive(Clone))]
712struct FilePathError {
713#[cfg(feature = "std")]
714path: std::path::PathBuf,
715}
716717impl core::error::Errorfor FilePathError {}
718719impl core::fmt::Displayfor FilePathError {
720fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
721#[cfg(feature = "std")]
722{
723self.path.display().fmt(f)
724 }
725#[cfg(not(feature = "std"))]
726{
727 f.write_str("<BUG: SHOULD NOT EXIST>")
728 }
729 }
730}
731732impl core::fmt::Debugfor FilePathError {
733fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
734#[cfg(feature = "std")]
735{
736f.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}
744745#[cfg(feature = "defmt")]
746impl defmt::Format for FilePathError {
747fn 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.
751defmt::write!(f, "FilePathError(unavailable)");
752 }
753}
754755/// 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 {
764fn into_error(self) -> Error;
765}
766767impl IntoErrorfor Error {
768#[inline(always)]
769fn into_error(self) -> Error {
770self771 }
772}
773774// 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 IntoErrorfor jcore::bounds::RangeError {
777#[inline(always)]
778fn into_error(self) -> Error {
779Error::jcore_range(self)
780 }
781}
782783/// 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.)
799fn context(self, consequent: impl IntoError) -> Result<T, Error>;
800801/// 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.
810fn with_context<C: IntoError>(
811self,
812 consequent: impl FnOnce() -> C,
813 ) -> Result<T, Error>;
814}
815816impl<T, E> ErrorContext<T, E> for Result<T, E>
817where
818E: IntoError,
819{
820#[cfg_attr(feature = "perf-inline", inline(always))]
821fn context(self, consequent: impl IntoError) -> Result<T, Error> {
822self.map_err(|err| {
823err.into_error().context_impl(consequent.into_error())
824 })
825 }
826827#[cfg_attr(feature = "perf-inline", inline(always))]
828fn with_context<C: IntoError>(
829self,
830 consequent: impl FnOnce() -> C,
831 ) -> Result<T, Error> {
832self.map_err(|err| {
833err.into_error().context_impl(consequent().into_error())
834 })
835 }
836}
837838#[cfg(test)]
839mod tests {
840use super::*;
841842// 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]
847fn error_size() {
848if cfg!(feature = "alloc") {
849let expected_size = core::mem::size_of::<usize>();
850assert_eq!(expected_size, core::mem::size_of::<Error>());
851return;
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.
890let got = core::mem::size_of::<Error>();
891assert!(got <= 40, "wanted error size to be <= 40, but got {got}");
892 }
893}