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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
//! This library provides very simple chainable error type `ChainedError` and some related traits.
//! # Example
//! ```
//! extern crate error_chain_mini;
//! #[macro_use]
//! extern crate error_chain_mini_derive;
//! use std::io;
//! use error_chain_mini::*;
//! #[derive(ErrorKind)]
//! enum MyErrorKind {
//!     #[msg(short = "io error", detailed = "inner: {:?}", _0)]
//!     IoError(io::Error),
//!     #[msg(short = "index error", detailed = "invalid index: {:?}", _0)]
//!     IndexEroor(usize),
//!     #[msg(short = "trivial error")]
//!     TrivialError,
//! }
//! type MyError = ChainedError<MyErrorKind>;
//! type MyResult<T> = Result<T, MyError>;
//! fn always_fail() -> MyResult<()> {
//!     Err(MyErrorKind::TrivialError.into_with(|| "Oh my god!"))
//! }
//! fn main() {
//!     assert_eq!("index error { invalid index: 10 }", MyErrorKind::IndexEroor(10).full());
//!     let chained = always_fail().chain_err(|| "Error in main()");
//!     assert!(chained.is_err());
//!     if let Err(chained) = chained {
//!         let mut cxts = chained.contexts();
//!         assert_eq!(cxts.next().unwrap(), "Oh my god!");
//!         assert_eq!(cxts.next().unwrap(), "Error in main()");
//!     }
//! }
//! ```

use std::error::Error;
use std::fmt::{self, Debug, Display, Formatter};

/// Error kind type.
///
/// You can implement `short`, which is exepected to return short hand description about error kind.
///
/// In addition, you can implement detailed description by `detailed`, but it's optional.
/// # Example
/// ```
/// # extern crate error_chain_mini; fn main() {
/// use std::io;
/// use std::fs::File;
/// use std::error::Error;
/// use error_chain_mini::{ErrorKind, ResultExt};
/// enum MyErrorKind {
///     IoError(io::Error),
///     IndexEroor(usize),
/// }
/// impl ErrorKind for MyErrorKind {
///     fn short(&self) -> &str {
///         match *self {
///             MyErrorKind::IoError(_) => "io error",
///             MyErrorKind::IndexEroor(_) => "index error"
///         }
///     }
/// }
/// impl From<io::Error> for MyErrorKind {
///     fn from(e: io::Error) -> Self {
///         MyErrorKind::IoError(e)
///     }
/// }
/// let file = File::open("not_existing_file").into_chained(|| "In io()");
/// assert!(file.is_err());
/// if let Err(e) = file {
///     assert_eq!(e.description(), "io error");
///     if let MyErrorKind::IoError(ioerr) = e.kind() {
///         assert_eq!(format!("{}", ioerr), "No such file or directory (os error 2)");
///     } else {
///         panic!("error kind is incorrect");
///     }
///     assert_eq!(e.contexts().collect::<Vec<_>>(), vec!["In io()"])
/// }
/// # }
/// ```
///
/// Instead of implement `ErrorKind`, you can use derive.
/// In this case, if you don't write `#[msg..` attribute, full path of the variant
/// (e.g. `MyErrorKind::IndexError`) is used for the return value of `short`.
///
/// **Notes**
/// If you derive `ErrorKind` for type A, `std::fmt::Display` is automatically implemented
/// for convinience.
///
/// # Example
/// ```
/// # extern crate error_chain_mini;
/// # #[macro_use] extern crate error_chain_mini_derive;
/// # fn main() {
/// use std::io;
/// use std::fs::File;
/// use std::error::Error;
/// use error_chain_mini::{ErrorKind, ResultExt};
/// #[derive(ErrorKind)]
/// enum MyErrorKind {
///     IoError(io::Error),
///     IndexEroor(usize),
/// }
/// impl From<io::Error> for MyErrorKind {
///     fn from(e: io::Error) -> Self {
///         MyErrorKind::IoError(e)
///     }
/// }
/// let file = File::open("not_existing_file").into_chained(|| "In io()");
/// assert!(file.is_err());
/// if let Err(e) = file {
///     assert_eq!(e.description(), "MyErrorKind::IoError");
///     assert_eq!(format!("{}", e.kind()), "MyErrorKind::IoError");
///     if let MyErrorKind::IoError(ioerr) = e.kind() {
///         assert_eq!(format!("{}", ioerr), "No such file or directory (os error 2)");
///     } else {
///         panic!("error kind is incorrect");
///     }
///     assert_eq!(e.contexts().collect::<Vec<_>>(), vec!["In io()"])
/// }
/// # }
/// ```
pub trait ErrorKind {
    /// Short description of error type, compatible with `std::error::Error::description`.
    ///
    /// To avoid duplication of implement same message, we have 2 message type short/detailed.
    ///
    /// Actually, `"{}: {}", ErrorKind::short(), ErrorKind::detailed()"` is used for display
    /// and you can also get full error message by `full` method.
    fn short(&self) -> &str;

    /// Detailed description of error type.
    fn detailed(&self) -> String {
        String::new()
    }
    /// Return full error message as String.
    ///
    /// **Notes** Do not overrride this method.
    /// # Usage
    /// ```
    /// # extern crate error_chain_mini;
    /// # #[macro_use] extern crate error_chain_mini_derive;
    /// # fn main() {
    /// use error_chain_mini::*;
    /// #[derive(ErrorKind, Eq, PartialEq, Debug)]
    /// #[msg(short = "My Error", detailed = "value: {}", value)]
    /// struct MyError {
    ///     value: usize,
    /// }
    /// let err = MyError { value: 320 };
    /// assert_eq!(format!("{}", err), err.full());
    /// # }
    /// ```
    fn full(&self) -> String {
        let detailed = self.detailed();
        if detailed.is_empty() {
            self.short().to_string()
        } else {
            format!("{} {{ {} }}", self.short(), self.detailed())
        }
    }

    /// Get [ChainedError](struct.ChainedError.html) with no context.
    ///
    /// Do not overrride this method.
    /// # Usage
    /// ```
    /// # extern crate error_chain_mini;
    /// # #[macro_use] extern crate error_chain_mini_derive;
    /// # use error_chain_mini::*; fn main() {
    /// #[derive(Clone, Copy, ErrorKind, Eq, PartialEq, Debug)]
    /// struct MyError;
    /// let chained = MyError{}.into_err();
    /// assert_eq!(*chained.kind(), MyError {});
    /// # }
    /// ```
    fn into_err(self) -> ChainedError<Self>
    where
        Self: Sized,
    {
        ChainedError::new(self, vec![])
    }

    /// Get [ChainedError](struct.ChainedError.html) with a context.
    ///
    /// Do not overrride this method.
    /// # Usage
    /// ```
    /// # extern crate error_chain_mini;
    /// # #[macro_use] extern crate error_chain_mini_derive;
    /// # use error_chain_mini::*; fn main() {
    /// fn my_func() {
    ///     #[derive(Clone, Copy, ErrorKind, Eq, PartialEq, Debug)]
    ///     struct MyError;
    ///     let chained = MyError{}.into_with(|| "Error in my_func");
    ///     assert_eq!(*chained.kind(), MyError {});
    ///     assert_eq!(chained.contexts().nth(0).unwrap(), "Error in my_func");
    /// }
    /// # }
    /// ```
    fn into_with<C: ErrorContext, F>(self, op: F) -> ChainedError<Self>
    where
        F: FnOnce() -> C,
        Self: Sized,
    {
        ChainedError::new(self, vec![Box::new(op())])
    }
}

/// Error context type.
///
/// Expected usage is use string as context.
///
/// See module level documentation for usage.
pub trait ErrorContext: 'static {
    fn context(&self) -> &str;
}

impl<S: 'static + AsRef<str>> ErrorContext for S {
    fn context(&self) -> &str {
        self.as_ref()
    }
}

/// Chainable error type.
///
/// See module level documentation for usage.
pub struct ChainedError<T: ErrorKind> {
    inner: Box<ErrorImpl<T>>,
}

impl<T: ErrorKind> Debug for ChainedError<T> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        Display::fmt(self, f)
    }
}

impl<T: ErrorKind> Error for ChainedError<T> {
    fn description(&self) -> &str {
        self.inner.kind.short()
    }
}

impl<T: ErrorKind> Display for ChainedError<T> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "\nkind: {}", self.inner.kind.short())?;
        let detailed = self.inner.kind.detailed();
        if !detailed.is_empty() {
            write!(f, " {{ {} }}", detailed)?;
        }
        writeln!(f)?;
        for (i, s) in self.inner.context.iter().enumerate() {
            if i != 0 {
                writeln!(f)?;
            }
            write!(f, "context{:3}: {}", i, s.context())?;
        }
        writeln!(f)
    }
}

impl<T: ErrorKind> ChainedError<T> {
    /// Create new ChainedError.
    pub fn new(kind: T, context: Vec<Box<ErrorContext>>) -> Self {
        ChainedError {
            inner: Box::new(ErrorImpl::new(kind, context)),
        }
    }

    /// Returns a reference of Error Kind
    /// # Usage
    /// ```
    /// # extern crate error_chain_mini;
    /// # #[macro_use] extern crate error_chain_mini_derive;
    /// # use error_chain_mini::*;
    /// # fn main() {
    /// #[derive(Debug, ErrorKind, Eq, PartialEq)]
    /// enum ErrorType {
    ///     A,
    ///     B,
    ///     C
    /// }
    /// let chained = ErrorType::B.into_err();
    /// assert_eq!(*chained.kind(), ErrorType::B);
    /// # }
    /// ```
    pub fn kind(&self) -> &T {
        &self.inner.kind
    }

    /// Returns a reference of Error Contexts
    /// Returns a reference of Error Kind
    /// # Usage
    /// ```
    /// # extern crate error_chain_mini;
    /// # #[macro_use] extern crate error_chain_mini_derive;
    /// # use error_chain_mini::*;
    /// # fn main() {
    /// #[derive(Debug, ErrorKind, Eq, PartialEq)]
    /// enum ErrorType {
    ///     A,
    ///     B,
    ///     C
    /// }
    /// let chained = ErrorType::B.into_with(|| "Error is Caused!");
    /// let chained = chained.chain(|| "Error is Chained!");
    /// let mut cxts = chained.contexts();
    /// assert_eq!(cxts.next().unwrap(), "Error is Caused!");
    /// assert_eq!(cxts.next().unwrap(), "Error is Chained!");
    /// # }
    /// ```
    pub fn contexts(&self) -> impl Iterator<Item = &str> {
        self.inner.context.iter().map(|cxt| cxt.context())
    }

    /// Add context to ChainedError by closure.
    ///
    /// It's more useful to use [chain_err](trait.ResultExt.html#tymethod.chain_err).
    pub fn chain<C, F>(mut self, op: F) -> Self
    where
        C: ErrorContext,
        F: FnOnce() -> C,
    {
        self.inner.context.push(Box::new(op()));
        self
    }

    /// Convert `ChainedError<T>` into `ChainedError<U>` using `std::convert::from`.
    ///
    /// # Usage
    ///
    /// ```
    /// # extern crate error_chain_mini;
    /// # #[macro_use] extern crate error_chain_mini_derive;
    /// # use error_chain_mini::*;
    /// mod external {
    /// #    use super::*;
    ///     #[derive(ErrorKind, Eq, PartialEq, Debug)]
    ///     #[msg(short = "error in external")]
    ///     pub struct ExtErrorKind;
    ///     pub type Error = ChainedError<ExtErrorKind>;
    ///     pub fn func() -> Result<(), Error> {
    ///         Err(ExtErrorKind{}.into_with(|| "In external::func()"))
    ///     }
    /// }
    /// # fn main() {
    /// use external::{self, ExtErrorKind};
    /// #[derive(ErrorKind, Eq, PartialEq, Debug)]
    /// enum MyErrorKind {
    ///     Internal,
    ///     #[msg(short = "from mod 'external'", detailed = "{:?}", _0)]
    ///     External(ExtErrorKind),
    /// };
    /// impl From<ExtErrorKind> for MyErrorKind {
    ///     fn from(e: ExtErrorKind) -> MyErrorKind {
    ///         MyErrorKind::External(e)
    ///     }
    /// }
    /// type Error = ChainedError<MyErrorKind>;
    /// let chained: Result<(), Error>
    ///     = external::func().map_err(|e| e.convert().chain(|| "In my_func()"));
    /// if let Err(chained) = chained {
    ///     assert_eq!(*chained.kind(), MyErrorKind::External(ExtErrorKind {}));
    ///     assert_eq!(chained.contexts().nth(1).unwrap(), "In my_func()");
    /// }
    /// # }
    /// ```    
    pub fn convert<U>(self) -> ChainedError<U>
    where
        U: ErrorKind + From<T>,
    {
        ChainedError {
            inner: Box::new(self.inner.convert(U::from)),
        }
    }

    /// Convert `ChainedError<T>` into `ChainedError<U>` using closure.
    ///
    /// # Usage
    ///
    /// ```
    /// # extern crate error_chain_mini;
    /// # #[macro_use] extern crate error_chain_mini_derive;
    /// # use error_chain_mini::*;
    /// mod external {
    /// #    use super::*;
    ///     #[derive(ErrorKind, Eq, PartialEq, Debug)]
    ///     #[msg(short = "error in external")]
    ///     pub struct ExtErrorKind;
    ///     pub type Error = ChainedError<ExtErrorKind>;
    ///     pub fn func() -> Result<(), Error> {
    ///         Err(ExtErrorKind{}.into_with(|| "In external::func()"))
    ///     }
    /// }
    /// # fn main() {
    /// use external::{self, ExtErrorKind};
    /// #[derive(ErrorKind, Eq, PartialEq, Debug)]
    /// enum MyErrorKind {
    ///     Internal,
    ///     #[msg(short = "from mod 'external'", detailed = "{:?}", _0)]
    ///     External(ExtErrorKind),
    /// };
    /// type Error = ChainedError<MyErrorKind>;
    /// let chained: Result<(), Error> = external::func().map_err(|e| {
    ///         e.convert_with(|e| MyErrorKind::External(e))
    ///          .chain(|| "In my_func()")
    ///    });
    /// if let Err(chained) = chained {
    ///     assert_eq!(*chained.kind(), MyErrorKind::External(ExtErrorKind {}));
    ///     assert_eq!(chained.contexts().nth(1).unwrap(), "In my_func()");
    /// }
    /// # }
    /// ```
    pub fn convert_with<U, F>(self, converter: F) -> ChainedError<U>
    where
        U: ErrorKind,
        F: FnOnce(T) -> U,
    {
        ChainedError {
            inner: Box::new(self.inner.convert(converter)),
        }
    }
}

struct ErrorImpl<T> {
    kind: T,
    context: Vec<Box<ErrorContext>>,
}

impl<T> ErrorImpl<T> {
    fn new(kind: T, context: Vec<Box<ErrorContext>>) -> Self {
        ErrorImpl { kind, context }
    }
    fn convert<F, U>(self, f: F) -> ErrorImpl<U>
    where
        F: FnOnce(T) -> U,
    {
        ErrorImpl::new(f(self.kind), self.context)
    }
}

unsafe impl<T: ErrorKind + Sync> Sync for ErrorImpl<T> {}
unsafe impl<T: ErrorKind + Send> Send for ErrorImpl<T> {}

/// `Result` extension to integrate with `ChainedError`
pub trait ResultExt {
    type OkType;
    type ErrType;
    /// Almost same as `chain_err`, but takes closure.
    /// If you want to do expensive operation like `format!` to generate error message,
    /// use this method instead of `chain_err`.
    /// # Usage
    /// ```
    /// # extern crate error_chain_mini;
    /// # #[macro_use] extern crate error_chain_mini_derive;
    /// # fn main() {
    /// use error_chain_mini::*;
    /// #[derive(ErrorKind, Eq, PartialEq, Debug)]
    /// #[msg(short = "My Error")]
    /// struct MyError;
    /// fn my_func() -> Result<(), ChainedError<MyError>>{
    ///     let chained = MyError{}.into_with(|| "Error in my_func");
    ///     Err(chained)
    /// }
    /// let chained = my_func().chain_err(|| "Chained");
    /// assert!(chained.is_err());
    /// if let Err(e) = chained {
    ///     let msg = format!("{}", e);
    ///     assert_eq!(msg, r#"
    /// kind: My Error
    /// context  0: Error in my_func
    /// context  1: Chained
    /// "#);
    /// }
    /// # }
    /// ```
    fn chain_err<C, K, F>(self, op: F) -> Result<Self::OkType, ChainedError<K>>
    where
        F: FnOnce() -> C,
        K: ErrorKind,
        C: ErrorContext,
        Self::ErrType: Into<ChainedError<K>>;

    /// Takes Result and context then convert its error type into `ChainedError` with  context.
    /// # Usage
    /// ```
    /// # extern crate error_chain_mini;
    /// # #[macro_use] extern crate error_chain_mini_derive;
    /// # fn main() {
    /// use error_chain_mini::*;
    /// use std::io;
    /// use std::fs::File;
    /// #[derive(Debug, ErrorKind)]
    /// enum MyError {
    ///     #[msg(short = "io error", detailed = "{:?}", _0)]
    ///     Io(io::Error),
    ///     Misc
    /// }
    /// impl From<io::Error> for MyError {
    ///     fn from(e: io::Error) -> Self {
    ///         MyError::Io(e)
    ///     }
    /// }
    /// let file: Result<_, ChainedError<MyError>> = File::open("not_existing_file").into_chained(|| "In io()");
    /// # }
    /// ```
    fn into_chained<C, K, F>(self, op: F) -> Result<Self::OkType, ChainedError<K>>
    where
        F: FnOnce() -> C,
        K: ErrorKind + From<Self::ErrType>,
        C: ErrorContext;

    /// Convert `Result<Ok, ChainedError<T>>` into `Result<Ok, ChainedError<U>>` using `std::convert::From`.
    ///
    /// # Usage
    ///
    /// ```
    /// # extern crate error_chain_mini;
    /// # #[macro_use] extern crate error_chain_mini_derive;
    /// # use error_chain_mini::*;
    /// mod external {
    /// #    use super::*;
    ///     #[derive(ErrorKind, Eq, PartialEq, Debug)]
    ///     #[msg(short = "error in external")]
    ///     pub struct ExtErrorKind;
    ///     pub type Error = ChainedError<ExtErrorKind>;
    ///     pub fn func() -> Result<(), Error> {
    ///         Err(ExtErrorKind{}.into_with(|| "In external::func()"))
    ///     }
    /// }
    /// # fn main() {
    /// use external::{self, ExtErrorKind};
    /// #[derive(ErrorKind, Eq, PartialEq, Debug)]
    /// enum MyErrorKind {
    ///     Internal,
    ///     #[msg(short = "from mod 'external'", detailed = "{:?}", _0)]
    ///     External(ExtErrorKind),
    /// };
    /// impl From<ExtErrorKind> for MyErrorKind {
    ///     fn from(e: ExtErrorKind) -> MyErrorKind {
    ///         MyErrorKind::External(e)
    ///     }
    /// }
    /// type Error = ChainedError<MyErrorKind>;
    /// let chained: Result<(), Error> = external::func().convert();
    /// if let Err(chained) = chained {
    ///     assert_eq!(*chained.kind(), MyErrorKind::External(ExtErrorKind {}));
    /// }
    /// # }
    /// ```
    fn convert<K, U>(self) -> Result<Self::OkType, ChainedError<U>>
    where
        K: ErrorKind,
        Self::ErrType: Into<ChainedError<K>>,
        U: From<K> + ErrorKind;

    /// Convert `Result<Ok, ChainedError<T>>` into `Result<Ok, ChainedError<U>>` using closure.
    ///
    /// # Usage
    ///
    /// ```
    /// # extern crate error_chain_mini;
    /// # #[macro_use] extern crate error_chain_mini_derive;
    /// # use error_chain_mini::*;
    /// mod external {
    /// #    use super::*;
    ///     #[derive(ErrorKind, Eq, PartialEq, Debug)]
    ///     #[msg(short = "error in external")]
    ///     pub struct ExtErrorKind;
    ///     pub type Error = ChainedError<ExtErrorKind>;
    ///     pub fn func() -> Result<(), Error> {
    ///         Err(ExtErrorKind{}.into_with(|| "In external::func()"))
    ///     }
    /// }
    /// # fn main() {
    /// use external::{self, ExtErrorKind};
    /// #[derive(ErrorKind, Eq, PartialEq, Debug)]
    /// enum MyErrorKind {
    ///     Internal,
    ///     #[msg(short = "from mod 'external'", detailed = "{:?}", _0)]
    ///     External(ExtErrorKind),
    /// };
    /// type Error = ChainedError<MyErrorKind>;
    /// let chained: Result<(), Error>
    ///     = external::func().convert_with(|e| MyErrorKind::External(e));
    /// if let Err(chained) = chained {
    ///     assert_eq!(*chained.kind(), MyErrorKind::External(ExtErrorKind {}));
    /// }
    /// # }
    /// ```
    fn convert_with<K, U, F>(self, converter: F) -> Result<Self::OkType, ChainedError<U>>
    where
        K: ErrorKind,
        Self::ErrType: Into<ChainedError<K>>,
        U: ErrorKind,
        F: FnOnce(K) -> U;
}

impl<T, E> ResultExt for Result<T, E> {
    type OkType = T;
    type ErrType = E;

    fn chain_err<C, K, F>(self, op: F) -> Result<Self::OkType, ChainedError<K>>
    where
        F: FnOnce() -> C,
        K: ErrorKind,
        C: ErrorContext,
        Self::ErrType: Into<ChainedError<K>>,
    {
        self.map_err(|e| e.into().chain(op))
    }

    fn into_chained<C, K, F>(self, op: F) -> Result<Self::OkType, ChainedError<K>>
    where
        F: FnOnce() -> C,
        K: ErrorKind + From<Self::ErrType>,
        C: ErrorContext,
    {
        self.map_err(|e| K::from(e).into_with(op))
    }

    fn convert<K, U>(self) -> Result<Self::OkType, ChainedError<U>>
    where
        K: ErrorKind,
        Self::ErrType: Into<ChainedError<K>>,
        U: From<K> + ErrorKind,
    {
        self.map_err(|e| e.into().convert())
    }

    fn convert_with<K, U, F>(self, converter: F) -> Result<Self::OkType, ChainedError<U>>
    where
        K: ErrorKind,
        Self::ErrType: Into<ChainedError<K>>,
        U: ErrorKind,
        F: FnOnce(K) -> U,
    {
        self.map_err(|e| e.into().convert_with(converter))
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::io::Error as IoError;
    enum MyErrorKind {
        Io(IoError),
        Index(usize),
    }
    impl ErrorKind for MyErrorKind {
        fn short(&self) -> &str {
            match self {
                MyErrorKind::Io(_) => "io error",
                MyErrorKind::Index(_) => "index error",
            }
        }
        fn detailed(&self) -> String {
            match *self {
                MyErrorKind::Io(ref io) => format!("{:?}", io),
                MyErrorKind::Index(id) => format!("{}", id),
            }
        }
    }
    type MyError = ChainedError<MyErrorKind>;
    impl From<IoError> for MyErrorKind {
        fn from(e: IoError) -> Self {
            MyErrorKind::Io(e)
        }
    }
    fn index_err(u: usize) -> Result<u32, MyError> {
        let array = vec![3, 7, 9, 20];
        if let Some(u) = array.get(u) {
            Ok(*u)
        } else {
            Err(MyErrorKind::Index(u).into_with(|| "Invalid access in index_err()"))
        }
    }
    #[test]
    fn io() {
        use std::fs::File;
        let file = File::open("not_existing_file").into_chained(|| "In io()");
        assert!(file.is_err());
        if let Err(e) = file {
            if let MyErrorKind::Index(_) = e.kind() {
                panic!("error kind is incorrect");
            }
            assert_eq!(e.contexts().collect::<Vec<_>>(), vec!["In io()"])
        }
    }
    #[test]
    fn index() {
        let id = 8;
        let res = index_err(id).chain_err(|| "In index()");
        assert!(res.is_err());
        if let Err(e) = res {
            if let MyErrorKind::Index(u) = e.kind() {
                assert_eq!(*u, id);
            } else {
                panic!("error kind is incorrect");
            }
            assert_eq!(
                e.contexts().collect::<Vec<_>>(),
                vec![
                    "Invalid access in index_err()".to_owned(),
                    "In index()".to_owned(),
                ]
            );
        }
    }
    #[test]
    #[should_panic]
    fn display() {
        let id = 8;
        let res = index_err(id).chain_err(|| "In index()");
        res.unwrap();
    }
}