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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
/*!
This module defines the various error types that can be produced by a failed conversion.

In addition, it also defines some extension traits to make working with failable conversions more ergonomic (see the `Unwrap*` traits).
*/

use std::any::Any;
use std::error::Error;
use std::fmt::{self, Debug, Display};
use misc::{Saturated, InvalidSentinel, SignedInfinity};

macro_rules! Desc {
    (
        ($desc:expr)
        pub struct $name:ident<$t:ident> $_body:tt;
    ) => {
        impl<$t> Display for $name<$t> {
            fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
                write!(fmt, $desc)
            }
        }

        impl<$t> Error for $name<$t> where $t: Any {
            fn description(&self) -> &str {
                $desc
            }
        }
    };
}

macro_rules! DummyDebug {
    (
        () pub enum $name:ident<$t:ident> {
            $(#[doc=$_doc:tt] $vname:ident($_vpay:ident),)+
        }
    ) => {
        impl<$t> Debug for $name<$t> {
            fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
                let msg = match *self {
                    $($name::$vname(_) => stringify!($vname),)+
                };
                write!(fmt, concat!(stringify!($name), "::{}(..)"), msg)
            }
        }
    };

    (
        () pub struct $name:ident<$t:ident>(pub $_pay:ident);
    ) => {
        impl<$t> Debug for $name<$t> {
            fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
                write!(fmt, concat!(stringify!($name), "(..)"))
            }
        }
    };
}

macro_rules! EnumDesc {
    (
        ($($vname:ident => $vdesc:expr,)+) 
        pub enum $name:ident $_body:tt
    ) => {
        impl Display for $name {
            fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
                write!(fmt, "{}",
                    match *self { $($name::$vname => $vdesc,)+ })
            }
        }

        impl Error for $name {
            fn description(&self) -> &str {
                match *self { $($name::$vname => $vdesc,)+ }
            }
        }
    };

    (
        ($($vname:ident => $vdesc:expr,)+) 
        pub enum $name:ident<$t:ident> $_body:tt
    ) => {
        impl<$t> Display for $name<$t> {
            fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
                write!(fmt, "{}",
                    match *self { $($name::$vname(..) => $vdesc,)+ })
            }
        }

        impl<$t> Error for $name<$t> where $t: Any {
            fn description(&self) -> &str {
                match *self { $($name::$vname(..) => $vdesc,)+ }
            }
        }
    };
}

macro_rules! FromName {
    (
        ($fname:ident)
        pub enum $name:ident<$t:ident> $_body:tt
    ) => {
        impl<$t> From<$fname<$t>> for $name<$t> {
            #[inline]
            fn from(e: $fname<$t>) -> Self {
                $name::$fname(e.into_inner())
            }
        }
    };

    (
        ($fname:ident<$t:ident>)
        pub enum $name:ident $_body:tt
    ) => {
        impl<$t> From<$fname<$t>> for $name {
            #[inline]
            fn from(_: $fname<$t>) -> Self {
                $name::$fname
            }
        }
    };
}

macro_rules! FromNoError {
    (
        () pub enum $name:ident $_body:tt
    ) => {
        impl From<NoError> for $name {
            #[inline]
            fn from(_: NoError) -> Self {
                panic!(concat!("cannot convert NoError into ", stringify!($name)))
            }
        }
    };

    (
        () pub enum $name:ident<$t:ident> $_body:tt
    ) => {
        impl<$t> From<NoError> for $name<$t> {
            fn from(_: NoError) -> Self {
                panic!(concat!("cannot convert NoError into ", stringify!($name)))
            }
        }
    };

    (
        () pub struct $name:ident<$t:ident> $_body:tt;
    ) => {
        impl<$t> From<NoError> for $name<$t> {
            fn from(_: NoError) -> Self {
                panic!(concat!("cannot convert NoError into ", stringify!($name)))
            }
        }
    };
}

macro_rules! FromRemap {
    (
        ($from:ident($($vname:ident),+))
        pub enum $name:ident $_body:tt
    ) => {
        impl From<$from> for $name {
            #[inline]
            fn from(e: $from) -> Self {
                match e {
                    $($from::$vname => $name::$vname,)+
                }
            }
        }
    };

    (
        ($from:ident<$t:ident>($($vname:ident),+))
        pub enum $name:ident $_body:tt
    ) => {
        impl<$t> From<$from<$t>> for $name {
            #[inline]
            fn from(e: $from<$t>) -> Self {
                match e {
                    $($from::$vname(..) => $name::$vname,)+
                }
            }
        }
    };

    (
        ($from:ident($($vname:ident),+))
        pub enum $name:ident<$t:ident> $_body:tt
    ) => {
        impl<$t> From<$from<$t>> for $name<$t> {
            #[inline]
            fn from(e: $from<$t>) -> Self {
                match e {
                    $($from::$vname(v) => $name::$vname(v),)+
                }
            }
        }
    };
}

macro_rules! IntoInner {
    (
        () pub enum $name:ident<$t:ident> {
            $(#[doc=$_doc:tt] $vname:ident($_vpay:ident),)+
        }
    ) => {
        impl<$t> $name<$t> {
            /// Returns the value stored in this error.
            #[inline]
            pub fn into_inner(self) -> $t {
                match self { $($name::$vname(v))|+ => v }
            }
        }
    };

    (
        () pub struct $name:ident<$t:ident>(pub $_pay:ident);
    ) => {
        impl<$t> $name<$t> {
            /// Returns the value stored in this error.
            #[inline]
            pub fn into_inner(self) -> $t {
                self.0
            }
        }
    };
}

custom_derive!{
    /**
    A general error enumeration that subsumes all other conversion errors.

    This exists primarily as a "catch-all" for reliably unifying various different kinds of conversion errors.
    */
    #[derive(
        Copy, Clone, Eq, PartialEq, Ord, PartialOrd,
        IntoInner, DummyDebug, FromNoError,
        EnumDesc(
            NegOverflow => "conversion resulted in negative overflow",
            PosOverflow => "conversion resulted in positive overflow",
            Unrepresentable => "could not convert unrepresentable value",
        ),
        FromName(Unrepresentable),
        FromName(NegOverflow),
        FromName(PosOverflow),
        FromRemap(RangeError(NegOverflow, PosOverflow))
    )]
    pub enum GeneralError<T> {
        /// Input was too negative for the target type.
        NegOverflow(T),

        /// Input was too positive for the target type.
        PosOverflow(T),

        /// Input was not representable in the target type.
        Unrepresentable(T),
    }
}

impl<T> From<FloatError<T>> for GeneralError<T> {
    #[inline]
    fn from(e: FloatError<T>) -> GeneralError<T> {
        use self::FloatError as F;
        use self::GeneralError as G;
        match e {
            F::NegOverflow(v) => G::NegOverflow(v),
            F::PosOverflow(v) => G::PosOverflow(v),
            F::NotANumber(v) => G::Unrepresentable(v),
        }
    }
}

custom_derive! {
    /**
    A general error enumeration that subsumes all other conversion errors, but discards all input payloads the errors may be carrying.

    This exists primarily as a "catch-all" for reliably unifying various different kinds of conversion errors, and between different input types.
    */
    #[derive(
        Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug,
        FromNoError,
        EnumDesc(
            NegOverflow => "conversion resulted in negative overflow",
            PosOverflow => "conversion resulted in positive overflow",
            Unrepresentable => "could not convert unrepresentable value",
        ),
        FromName(Unrepresentable<T>),
        FromName(NegOverflow<T>),
        FromName(PosOverflow<T>),
        FromRemap(RangeErrorKind(NegOverflow, PosOverflow)),
        FromRemap(RangeError<T>(NegOverflow, PosOverflow)),
        FromRemap(GeneralError<T>(NegOverflow, PosOverflow, Unrepresentable))
    )]
    pub enum GeneralErrorKind {
        /// Input was too negative for the target type.
        NegOverflow,

        /// Input was too positive for the target type.
        PosOverflow,

        /// Input was not representable in the target type.
        Unrepresentable,
    }
}

impl<T> From<FloatError<T>> for GeneralErrorKind {
    #[inline]
    fn from(e: FloatError<T>) -> GeneralErrorKind {
        use self::FloatError as F;
        use self::GeneralErrorKind as G;
        match e {
            F::NegOverflow(..) => G::NegOverflow,
            F::PosOverflow(..) => G::PosOverflow,
            F::NotANumber(..) => G::Unrepresentable,
        }
    }
}

/**
Indicates that it is not possible for the conversion to fail.

You can use the [`UnwrapOk::unwrap_ok`](./trait.UnwrapOk.html#tymethod.unwrap_ok) method to discard the (statically impossible) `Err` case from a `Result<_, NoError>`, without using `Result::unwrap` (which is typically viewed as a "code smell").
*/
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
pub enum NoError {}

impl Display for NoError {
    fn fmt(&self, _: &mut fmt::Formatter) -> Result<(), fmt::Error> {
        unreachable!()
    }
}

impl Error for NoError {
    fn description(&self) -> &str {
        unreachable!()
    }
}

custom_derive! {
    /// Indicates that the conversion failed because the value was not representable.
    #[derive(
        Copy, Clone, Eq, PartialEq, Ord, PartialOrd,
        IntoInner, DummyDebug, FromNoError,
        Desc("could not convert unrepresentable value")
    )]
    pub struct Unrepresentable<T>(pub T);
}

custom_derive! {
    /// Indicates that the conversion failed due to a negative overflow.
    #[derive(
        Copy, Clone, Eq, PartialEq, Ord, PartialOrd,
        IntoInner, DummyDebug, FromNoError,
        Desc("conversion resulted in negative overflow")
    )]
    pub struct NegOverflow<T>(pub T);
}

custom_derive! {
    /// Indicates that the conversion failed due to a positive overflow.
    #[derive(
        Copy, Clone, Eq, PartialEq, Ord, PartialOrd,
        IntoInner, DummyDebug, FromNoError,
        Desc("conversion resulted in positive overflow")
    )]
    pub struct PosOverflow<T>(pub T);
}

custom_derive! {
    /**
    Indicates that a conversion from a floating point type failed.
    */
    #[derive(
        Copy, Clone, Eq, PartialEq, Ord, PartialOrd,
        IntoInner, DummyDebug, FromNoError,
        EnumDesc(
            NegOverflow => "conversion resulted in negative overflow",
            PosOverflow => "conversion resulted in positive overflow",
            NotANumber => "conversion target does not support not-a-number",
        ),
        FromName(NegOverflow),
        FromName(PosOverflow),
        FromRemap(RangeError(NegOverflow, PosOverflow))
    )]
    pub enum FloatError<T> {
        /// Input was too negative for the target type.
        NegOverflow(T),

        /// Input was too positive for the target type.
        PosOverflow(T),

        /// Input was not-a-number, which the target type could not represent.
        NotANumber(T),
    }
}

custom_derive! {
    /**
    Indicates that a conversion failed due to a range error.
    */
    #[derive(
        Copy, Clone, Eq, PartialEq, Ord, PartialOrd,
        IntoInner, DummyDebug, FromNoError,
        EnumDesc(
            NegOverflow => "conversion resulted in negative overflow",
            PosOverflow => "conversion resulted in positive overflow",
        ),
        FromName(NegOverflow),
        FromName(PosOverflow)
    )]
    pub enum RangeError<T> {
        /// Input was too negative for the target type.
        NegOverflow(T),

        /// Input was too positive the target type.
        PosOverflow(T),
    }
}

custom_derive! {
    /**
    Indicates that a conversion failed due to a range error.

    This is a variant of `RangeError` that does not retain the input value which caused the error.  It exists to help unify some utility methods and should not generally be used directly, unless you are targeting the `Unwrap*` traits.
    */
    #[derive(
        Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug,
        FromNoError,
        EnumDesc(
            NegOverflow => "conversion resulted in negative overflow",
            PosOverflow => "conversion resulted in positive overflow",
        ),
        FromName(NegOverflow<T>),
        FromName(PosOverflow<T>),
        FromRemap(RangeError<T>(NegOverflow, PosOverflow))
    )]
    pub enum RangeErrorKind {
        /// Input was too negative for the target type.
        NegOverflow,

        /// Input was too positive for the target type.
        PosOverflow,
    }
}

/**
Saturates a `Result`.
*/
pub trait Saturate {
    /// The result of saturating.
    type Output;

    /**
    Replaces an overflow error with a saturated value.

    Unlike `unwrap_or_saturate`, this method can be used in cases where the `Result` error type can encode failures *other* than overflow and underflow.  For example, you cannot saturate a float-to-integer conversion using `unwrap_or_saturate` as the error might be `NotANumber`, which doesn't have a meaningful saturation "direction".

    The output of this method will be a `Result` where the error type *does not* contain overflow conditions.  What conditions remain must still be dealt with in some fashion.
    */
    fn saturate(self) -> Self::Output;
}

impl<T, U> Saturate for Result<T, FloatError<U>>
where T: Saturated {
    type Output = Result<T, Unrepresentable<U>>;

    #[inline]
    fn saturate(self) -> Self::Output {
        use self::FloatError::*;
        match self {
            Ok(v) => Ok(v),
            Err(NegOverflow(_)) => Ok(T::saturated_min()),
            Err(PosOverflow(_)) => Ok(T::saturated_max()),
            Err(NotANumber(v)) => Err(Unrepresentable(v))
        }
    }
}

impl<T, U> Saturate for Result<T, RangeError<U>>
where T: Saturated {
    type Output = Result<T, NoError>;

    #[inline]
    fn saturate(self) -> Self::Output {
        use self::RangeError::*;
        match self {
            Ok(v) => Ok(v),
            Err(NegOverflow(_)) => Ok(T::saturated_min()),
            Err(PosOverflow(_)) => Ok(T::saturated_max())
        }
    }
}

impl<T> Saturate for Result<T, RangeErrorKind>
where T: Saturated {
    type Output = Result<T, NoError>;

    #[inline]
    fn saturate(self) -> Self::Output {
        use self::RangeErrorKind::*;
        match self {
            Ok(v) => Ok(v),
            Err(NegOverflow) => Ok(T::saturated_min()),
            Err(PosOverflow) => Ok(T::saturated_max())
        }
    }
}

/**
Safely unwrap a `Result` that cannot contain an error.
*/
pub trait UnwrapOk<T> {
    /**
    Unwraps a `Result` without possibility of failing.

    Technically, this is not necessary; it's provided simply to make user code a little clearer.
    */
    fn unwrap_ok(self) -> T;
}

impl<T> UnwrapOk<T> for Result<T, NoError> {
    #[inline]
    fn unwrap_ok(self) -> T {
        match self {
            Ok(v) => v,
            Err(no_error) => match no_error {},
        }
    }
}

/**
Unwrap a conversion by saturating to infinity.
*/
pub trait UnwrapOrInf {
    /// The result of unwrapping.
    type Output;

    /**
    Either unwraps the successfully converted value, or saturates to infinity in the "direction" of overflow.
    */
    fn unwrap_or_inf(self) -> Self::Output;
}

/**
Unwrap a conversion by replacing a failure with an invalid sentinel value.
*/
pub trait UnwrapOrInvalid {
    /// The result of unwrapping.
    type Output;

    /**
    Either unwraps the successfully converted value, or returns the output type's invalid sentinel value.
    */
    fn unwrap_or_invalid(self) -> Self::Output;
}

/**
Unwrap a conversion by saturating.
*/
pub trait UnwrapOrSaturate {
    /// The result of unwrapping.
    type Output;

    /**
    Either unwraps the successfully converted value, or saturates in the "direction" of overflow.
    */
    fn unwrap_or_saturate(self) -> Self::Output;
}

impl<T, E> UnwrapOrInf for Result<T, E>
where T: SignedInfinity, E: Into<RangeErrorKind> {
    type Output = T;
    #[inline]
    fn unwrap_or_inf(self) -> T {
        use self::RangeErrorKind::*;
        match self.map_err(Into::into) {
            Ok(v) => v,
            Err(NegOverflow) => T::neg_infinity(),
            Err(PosOverflow) => T::pos_infinity(),
        }
    }
}

impl<T, E> UnwrapOrInvalid for Result<T, E>
where T: InvalidSentinel {
    type Output = T;
    #[inline]
    fn unwrap_or_invalid(self) -> T {
        match self {
            Ok(v) => v,
            Err(..) => T::invalid_sentinel(),
        }
    }
}

impl<T, E> UnwrapOrSaturate for Result<T, E>
where T: Saturated, E: Into<RangeErrorKind> {
    type Output = T;
    #[inline]
    fn unwrap_or_saturate(self) -> T {
        use self::RangeErrorKind::*;
        match self.map_err(Into::into) {
            Ok(v) => v,
            Err(NegOverflow) => T::saturated_min(),
            Err(PosOverflow) => T::saturated_max(),
        }
    }
}