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