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
//! `safecast` defines traits analogous to [`From`], [`Into`], [`TryFrom`], and [`TryInto`] to
//! standardize the implementation of casting between Rust types. The `can_cast_from` and
//! `can_cast_into` methods borrow the source value, allowing pattern matching without moving.
//!
//! Example:
//! ```ignore
//! let value = serde_json::from_str("1");
//! if value.matches::<i32>() {
//!     println!("It's an integer!");
//! } else if value.matches::<String>() {
//!     let value = String::opt_cast_from(value).unwrap();
//!     println!("no, it's a string: {}", value);
//! }
//! ```

#[allow(unused_imports)]
use std::convert::{TryFrom, TryInto};

/// Trait for defining a cast operation from some source type `T`.
/// Analogous to [`std::convert::From`].
/// The inverse of [`CastInto`].
/// Prefer implementing `CastFrom` over `CastInto` because implementing `CastFrom` automatically
/// provides an implementation of `CastInto`.

pub trait CastFrom<T> {
    fn cast_from(value: T) -> Self;
}

/// Trait for defining a cast operation to some destination type T.
/// Analogous to [`std::convert::Into`].
/// The inverse of [`CastFrom`].
/// Prefer implementing `CastFrom` over `CastInto` because implementing `CastFrom` automatically
/// provides an implementation of `CastInto`.
pub trait CastInto<T> {
    fn cast_into(self) -> T;
}

impl<F, T: From<F>> CastFrom<F> for T {
    fn cast_from(f: F) -> T {
        T::from(f)
    }
}

impl<T, F: CastFrom<T>> CastInto<F> for T {
    fn cast_into(self) -> F {
        F::cast_from(self)
    }
}

/// Trait for defining a cast operation when the source type cannot always be cast to the
/// destination type. Defines a `can_cast_from` method which borrows the source value, allowing
/// for pattern matching without moving the value. When `can_cast_from` returns `true`, calling
/// `opt_cast_from` *must* return `Some(...)`, otherwise `try_cast_from` may panic.
///
/// Analogous to [`TryFrom`].
/// The inverse of [`TryCastInto`].
/// Prefer implementing `TryCastFrom` over `TryCastInto` because implementing `TryCastFrom`
/// automatically provides an implementation of `TryCastInto`.
pub trait TryCastFrom<T>: Sized {
    /// Test if `value` can be cast into `Self`.
    fn can_cast_from(value: &T) -> bool;

    /// Returns `Some(Self)` if the source value can be cast into `Self`, otherwise `None`.
    fn opt_cast_from(value: T) -> Option<Self>;

    /// Returns `Ok(Self)` if the source value can be cast into `Self`, otherwise calls `on_err`.
    fn try_cast_from<Err, OnErr: FnOnce(&T) -> Err>(value: T, on_err: OnErr) -> Result<Self, Err> {
        if Self::can_cast_from(&value) {
            Ok(Self::opt_cast_from(value).unwrap())
        } else {
            Err(on_err(&value))
        }
    }
}
/// Trait for defining a cast operation when the destination type cannot always be cast from the
/// source type. Defines a `can_cast_into` method which borrows `self`, allowing for pattern
/// matching without moving `self`. If `can_cast_into` returns `true`, then calling
/// `opt_cast_into` *must* return `Some(...)`, otherwise `try_cast_into` may panic.
///
/// Analogous to [`TryFrom`].
/// The inverse of [`TryCastInto`].
/// Prefer implementing `TryCastFrom` over `TryCastInto` because implementing `TryCastFrom`
/// automatically provides an implementation of `TryCastInto`.
pub trait TryCastInto<T>: Sized {
    /// Test if `self` can be cast into `T`.
    fn can_cast_into(&self) -> bool;

    /// Returns `Some(T)` if `self` can be cast into `T`, otherwise `None`.
    fn opt_cast_into(self) -> Option<T>;

    /// Returns `Ok(T)` if `self` can be cast into `T`, otherwise calls `on_err`.
    fn try_cast_into<Err, OnErr: FnOnce(&Self) -> Err>(self, on_err: OnErr) -> Result<T, Err> {
        if self.can_cast_into() {
            Ok(self.opt_cast_into().unwrap())
        } else {
            Err(on_err(&self))
        }
    }
}

impl<F, T: CastFrom<F>> TryCastFrom<F> for T {
    fn can_cast_from(_: &F) -> bool {
        true
    }

    fn opt_cast_from(f: F) -> Option<T> {
        Some(T::cast_from(f))
    }
}

impl<F, T: TryCastFrom<F>> TryCastInto<T> for F {
    fn can_cast_into(&self) -> bool {
        T::can_cast_from(self)
    }

    fn opt_cast_into(self) -> Option<T> {
        T::opt_cast_from(self)
    }
}

/// Blanket implementation of a convenience method `matches` which allows calling
/// `can_cast_from` with a type parameter. Do not implement this trait.
pub trait Match: Sized {
    /// Returns `true` if `self` can be cast into the target type `T`.
    fn matches<T: TryCastFrom<Self>>(&self) -> bool {
        T::can_cast_from(self)
    }
}

impl<F> Match for F {}

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

    struct CastError;

    struct Foo {
        a: i32,
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    struct Bar {
        b: u32,
    }

    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    struct Baz {
        bar: Bar,
    }

    impl CastFrom<Foo> for Bar {
        fn cast_from(foo: Foo) -> Self {
            Bar { b: foo.a as u32 }
        }
    }

    impl TryCastFrom<Bar> for Baz {
        fn can_cast_from(bar: &Bar) -> bool {
            bar.b == 0
        }

        fn opt_cast_from(bar: Bar) -> Option<Self> {
            if bar.b == 0 {
                Some(Self { bar })
            } else {
                None
            }
        }
    }

    #[test]
    fn test_cast() {
        let foo = Foo { a: 1 };
        assert_eq!(Bar::cast_from(foo), Bar { b: 1 })
    }

    #[test]
    fn test_matches() {
        let bar0 = Bar { b: 0 };
        let bar1 = Bar { b: 1 };
        assert!(bar0.matches::<Baz>());
        assert!(!bar1.matches::<Baz>());
    }

    #[test]
    fn test_try_cast() {
        let bar0 = Bar { b: 0 };
        let bar1 = Bar { b: 1 };

        assert_eq!(Baz::opt_cast_from(bar0), Some(Baz { bar: bar0 }));
        assert_eq!(Baz::opt_cast_from(bar1), None);

        assert!(Baz::try_cast_from(bar0, |_| CastError).is_ok());
        assert!(Baz::try_cast_from(bar1, |_| CastError).is_err());
    }
}