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