1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! # rancor
//!
//! rancor provides scalable and efficient error handling without using type
//! composition. This makes it best-suited for situations where:
//!
//! - Programmatic error introspection is not useful
//! - Functions may error, but succeed most of the time
//! - Errors should provide as much useful detail as possible when emitted
//! - Use cases include both `no_std` and targets with support for `std`
//!
//! ## Features
//!
//! - `alloc`: Provides the [`BoxedError`] type. Enabled by default.

#![deny(
    future_incompatible,
    missing_docs,
    nonstandard_style,
    unsafe_op_in_unsafe_fn,
    unused,
    warnings,
    clippy::all,
    clippy::missing_safety_doc,
    clippy::undocumented_unsafe_blocks,
    rustdoc::broken_intra_doc_links,
    rustdoc::missing_crate_level_docs
)]
#![no_std]
#![cfg_attr(all(docsrs, not(doctest)), feature(doc_cfg, doc_auto_cfg))]

#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(feature = "alloc")]
mod boxed_error;
#[cfg(feature = "alloc")]
mod thin_box;

use core::{
    error, fmt,
    hint::unreachable_unchecked,
    marker::PhantomData,
    ops::{Deref, DerefMut},
};

/// A type which can add an additional trace to itself.
pub trait Trace: Sized + Send + Sync + 'static {
    /// Adds an additional trace to this error, returning a new error.
    fn trace<R>(self, trace: R) -> Self
    where
        R: fmt::Debug + fmt::Display + Send + Sync + 'static;
}

/// An error type which can be uniformly constructed from an [`Error`] and
/// additional trace information.
pub trait Source: Trace + error::Error {
    /// Returns a new `Self` using the given [`Error`].
    ///
    /// Depending on the specific implementation, this may box the error,
    /// immediately emit a diagnostic, or discard it and only remember that some
    /// error occurred.
    fn new<T: error::Error + Send + Sync + 'static>(source: T) -> Self;
}

/// A type with fallible operations that return its associated error type.
pub trait Fallible {
    /// The error type associated with this type's operations.
    type Error;
}

/// Equips a type with a `Fallible` implementation that chooses `E` as its error
/// type.
#[repr(transparent)]
pub struct Strategy<T: ?Sized, E> {
    _error: PhantomData<E>,
    inner: T,
}

impl<T: ?Sized, E> Fallible for Strategy<T, E> {
    type Error = E;
}

impl<T: ?Sized, E> Strategy<T, E> {
    /// Wraps the given mutable reference, returning a mutable reference to a
    /// `Strategy`.
    ///
    /// ## Example
    /// ```
    /// use core::ops::Deref;
    ///
    /// use rancor::{Failure, Strategy};
    /// fn test() {
    ///     struct Inner {
    ///         value: u64,
    ///     }
    ///
    ///     let mut inner = Inner { value: 10 };
    ///
    ///     let inner_value_ptr = &inner.value as *const u64;
    ///     let strategy: &mut Strategy<Inner, Failure> =
    ///         Strategy::wrap(&mut inner);
    ///     let strategy_value_ptr = (&strategy.deref().value) as *const u64;
    ///     assert_eq!(inner_value_ptr, strategy_value_ptr);
    ///     // Strategy wraps a type but does not change its memory layout.
    /// }
    ///
    /// test();
    /// ```
    pub fn wrap(inner: &mut T) -> &mut Self {
        // SAFETY: `Strategy` is `repr(transparent)` and so has the same layout
        // as `T`. The input and output lifetimes are the same, so mutable
        // aliasing rules will be upheld. Finally, because the inner `T` is the
        // final element of `Strategy`, the pointer metadata of the two pointers
        // will be the same.
        unsafe { core::mem::transmute::<&mut T, &mut Self>(inner) }
    }
}

impl<T: ?Sized, E> Deref for Strategy<T, E> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<T: ?Sized, E> DerefMut for Strategy<T, E> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.inner
    }
}

/// Returns the given error from this function.
#[macro_export]
macro_rules! fail {
    ($($x:tt)*) => {
        return ::core::result::Result::Err($crate::Source::new($($x)*));
    };
}

/// Helper methods for `Result`s.
pub trait ResultExt<T, E> {
    /// Returns a `Result` with this error type converted to `U`.
    fn into_error<U>(self) -> Result<T, U>
    where
        U: Source,
        E: error::Error + Send + Sync + 'static;

    /// Returns a `Result` with this error type converted to `U` and with an
    /// additional `trace` message added.
    fn into_trace<U, R>(self, trace: R) -> Result<T, U>
    where
        U: Source,
        R: fmt::Debug + fmt::Display + Send + Sync + 'static,
        E: error::Error + Send + Sync + 'static;

    /// Returns a `Result` with this error type converted to `U` and with an
    /// additional trace message added by evaluating the given function `f`. The
    /// function is evaluated only if an error occurred.
    fn into_with_trace<U, R, F>(self, f: F) -> Result<T, U>
    where
        U: Source,
        R: fmt::Debug + fmt::Display + Send + Sync + 'static,
        F: FnOnce() -> R,
        E: error::Error + Send + Sync + 'static;

    /// Adds an additional `trace` message to the error value of this type.
    fn trace<R>(self, trace: R) -> Result<T, E>
    where
        R: fmt::Debug + fmt::Display + Send + Sync + 'static,
        E: Trace;

    /// Adds an additional trace message to the error value of this type by
    /// evaluating the given function `f`. The function is evaluated only if an
    /// error occurred.
    fn with_trace<R, F>(self, f: F) -> Result<T, E>
    where
        R: fmt::Debug + fmt::Display + Send + Sync + 'static,
        F: FnOnce() -> R,
        E: Trace;

    /// Safely unwraps a result that is always `Ok`.
    ///
    /// In order to call this method, the error type of this `Result` must be a
    /// [`Never`] type.
    fn always_ok(self) -> T
    where
        E: Never;
}

impl<T, E> ResultExt<T, E> for Result<T, E> {
    fn into_error<U>(self) -> Result<T, U>
    where
        U: Source,
        E: error::Error + Send + Sync + 'static,
    {
        match self {
            Ok(x) => Ok(x),
            Err(e) => Err(U::new(e)),
        }
    }

    fn into_trace<U, R>(self, trace: R) -> Result<T, U>
    where
        U: Source,
        R: fmt::Debug + fmt::Display + Send + Sync + 'static,
        E: error::Error + Send + Sync + 'static,
    {
        match self {
            Ok(x) => Ok(x),
            Err(e) => Err(U::new(e).trace(trace)),
        }
    }

    fn into_with_trace<U, R, F>(self, f: F) -> Result<T, U>
    where
        U: Source,
        R: fmt::Debug + fmt::Display + Send + Sync + 'static,
        F: FnOnce() -> R,
        E: error::Error + Send + Sync + 'static,
    {
        match self {
            Ok(x) => Ok(x),
            Err(e) => Err(U::new(e).trace(f())),
        }
    }

    fn trace<R>(self, trace: R) -> Result<T, E>
    where
        R: fmt::Debug + fmt::Display + Send + Sync + 'static,
        E: Trace,
    {
        match self {
            Ok(x) => Ok(x),
            Err(e) => Err(e.trace(trace)),
        }
    }

    fn with_trace<R, F>(self, f: F) -> Result<T, E>
    where
        R: fmt::Debug + fmt::Display + Send + Sync + 'static,
        F: FnOnce() -> R,
        E: Trace,
    {
        match self {
            Ok(x) => Ok(x),
            Err(e) => Err(e.trace(f())),
        }
    }

    fn always_ok(self) -> T
    where
        E: Never,
    {
        match self {
            Ok(x) => x,
            Err(e) => unreachable_checked(e),
        }
    }
}

/// Helper methods for `Option`s.
pub trait OptionExt<T> {
    /// Returns a `Result` with an error indicating that `Some` was expected but
    /// `None` was found.
    fn into_error<E>(self) -> Result<T, E>
    where
        E: Source;

    /// Returns a `Result` with an error indicating that `Some` was expected but
    /// `None` was found, and with an additional `trace` message added.
    fn into_trace<E, R>(self, trace: R) -> Result<T, E>
    where
        E: Source,
        R: fmt::Debug + fmt::Display + Send + Sync + 'static;

    /// Returns a `Result` with an error indicating that `Some` was expected but
    /// `None` was found, and with an additional trace message added by
    /// evaluating the given function `f`. The function is evaluated only if an
    /// error occurred.
    fn into_with_trace<E, R, F>(self, f: F) -> Result<T, E>
    where
        E: Source,
        R: fmt::Debug + fmt::Display + Send + Sync + 'static,
        F: FnOnce() -> R;
}

/// A type that can never be produced.
///
/// Never types include the unstable `!` type, enums with no variants, or any
/// type that always contains a never type (e.g. a struct with a `Never` field).
///
/// # Safety
///
/// It must be impossible to produce a value of this type.
pub unsafe trait Never {}

/// Consumes a `Never` type, returning a primitive `!`.
///
/// This is a safe version of [`unreachable_unchecked`] for `Never` types.
#[inline(always)]
pub const fn unreachable_checked<T: Never>(_: T) -> ! {
    // SAFETY: Types that implement `Never` cannot be constructed,
    // so this is unreachable.
    unsafe { unreachable_unchecked() }
}

#[derive(Debug)]
struct NoneError;

impl fmt::Display for NoneError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "`Option` is `None`, expected `Some`")
    }
}

impl error::Error for NoneError {}

impl<T> OptionExt<T> for Option<T> {
    fn into_error<E>(self) -> Result<T, E>
    where
        E: Source,
    {
        match self {
            Some(x) => Ok(x),
            None => Err(E::new(NoneError)),
        }
    }

    fn into_trace<E, R>(self, trace: R) -> Result<T, E>
    where
        E: Source,
        R: fmt::Debug + fmt::Display + Send + Sync + 'static,
    {
        match self {
            Some(x) => Ok(x),
            None => Err(E::new(NoneError).trace(trace)),
        }
    }

    fn into_with_trace<E, R, F>(self, f: F) -> Result<T, E>
    where
        E: Source,
        R: fmt::Debug + fmt::Display + Send + Sync + 'static,
        F: FnOnce() -> R,
    {
        match self {
            Some(x) => Ok(x),
            None => Err(E::new(NoneError).trace(f())),
        }
    }
}

pub use core::convert::Infallible;

// SAFETY: `Infallible` is an enum with no variants, and so cannot be produced.
unsafe impl Never for Infallible {}

impl Trace for Infallible {
    fn trace<R>(self, _: R) -> Self
    where
        R: fmt::Debug + fmt::Display + Send + Sync + 'static,
    {
        match self {}
    }
}

/// An error type that does not occupy any space, panicking on creation instead.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Panic {}

// SAFETY: `Panic` is an enum with no variants, and so cannot be produced.
unsafe impl Never for Panic {}

impl fmt::Display for Panic {
    fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {}
    }
}

impl error::Error for Panic {}

impl Trace for Panic {
    fn trace<R>(self, _: R) -> Self
    where
        R: fmt::Debug + fmt::Display + Send + Sync + 'static,
    {
        match self {}
    }
}

impl Source for Panic {
    fn new<T: fmt::Display>(error: T) -> Self {
        panic!("created a new `Panic` from: {error}");
    }
}

/// An error type that only preserves success or failure, throwing away any more
/// detailed error messages.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Failure;

impl fmt::Display for Failure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "failed without error information")
    }
}

impl error::Error for Failure {}

impl Trace for Failure {
    fn trace<R>(self, _: R) -> Self
    where
        R: fmt::Debug + fmt::Display + Send + Sync + 'static,
    {
        self
    }
}

impl Source for Failure {
    fn new<T: error::Error + Send + Sync + 'static>(_: T) -> Self {
        Self
    }
}

#[cfg(feature = "alloc")]
pub use boxed_error::BoxedError;

#[cfg(all(debug_assertions, feature = "alloc"))]
type ErrorType = BoxedError;
#[cfg(not(all(debug_assertions, feature = "alloc")))]
type ErrorType = Failure;

/// A good general-purpose error type.
///
/// If `debug_assertions` and the `alloc` feature are enabled, then this error
/// will have the same behavior as [`BoxedError`]. Otherwise, it will behave
/// like [`Failure`].
#[derive(Debug)]
pub struct Error {
    inner: ErrorType,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.inner)?;
        #[cfg(not(all(debug_assertions, feature = "alloc")))]
        write!(
            f,
            "; enable debug assertions and the `alloc` feature in rancor for \
             error information"
        )?;

        Ok(())
    }
}

impl error::Error for Error {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        self.inner.source()
    }
}

impl Trace for Error {
    fn trace<R>(self, trace: R) -> Self
    where
        R: fmt::Debug + fmt::Display + Send + Sync + 'static,
    {
        Self {
            inner: self.inner.trace(trace),
        }
    }
}

impl Source for Error {
    fn new<T: error::Error + Send + Sync + 'static>(source: T) -> Self {
        Self {
            inner: ErrorType::new(source),
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    struct Inner {
        value: u64,
    }

    #[test]
    fn test_strategy() {
        let mut inner = Inner { value: 10 };
        let address = &inner.value as *const u64;
        let strategy: &mut Strategy<Inner, Failure> =
            Strategy::wrap(&mut inner);
        let s_address = (&strategy.inner.value) as *const u64;
        assert_eq!(address, s_address);

        assert_eq!(strategy.value, 10);
        strategy.value = 20;
        assert_eq!(strategy.value, 20);
        assert_eq!(inner.value, 20);
    }
}