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
use serde::{ser, de}; use core::fmt; pub trait DisplayCollector { fn display<T>(msg: &T) -> Self where T: ?Sized + fmt::Display; } #[derive(Debug)] pub enum ErrorAdapter<E, D> where D: DisplayCollector, { Inner(E), Other(D), } impl<E, D> ser::Error for ErrorAdapter<E, D> where D: DisplayCollector + fmt::Display + fmt::Debug, E: fmt::Display + fmt::Debug, { fn custom<T>(msg: T) -> Self where T: fmt::Display, { use self::ErrorAdapter::*; Other(D::display(&msg)) } } impl<E, D> de::Error for ErrorAdapter<E, D> where D: DisplayCollector + fmt::Display + fmt::Debug, E: fmt::Display + fmt::Debug, { fn custom<T>(msg: T) -> Self where T: fmt::Display, { use self::ErrorAdapter::*; Other(D::display(&msg)) } } impl<E, D> fmt::Display for ErrorAdapter<E, D> where D: DisplayCollector + fmt::Display, E: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::ErrorAdapter::*; match self { &Inner(ref e) => write!(f, "{}", e), &Other(ref d) => write!(f, "{}", d), } } } #[cfg(feature = "use_std")] mod std { use std::{fmt, error, string}; use super::{ErrorAdapter, DisplayCollector}; impl<E, D> error::Error for ErrorAdapter<E, D> where D: DisplayCollector + fmt::Display + fmt::Debug, E: fmt::Display + fmt::Debug, {} impl DisplayCollector for string::String { fn display<T>(msg: &T) -> Self where T: ?Sized + fmt::Display, { format!("{}", msg) } } }