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
//! `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.

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

/// Conversion methods from a container type (such as an `enum`) and a target type `T`.
pub trait AsType<T>: From<T> {
    /// Borrow this instance as an instance of `T` if possible.
    fn as_type(&self) -> Option<&T>;

    /// Borrow this instance mutably as an instance of `T` if possible.
    fn as_type_mut(&mut self) -> Option<&mut T>;

    /// Convert this instance into an instance of `T` if possible.
    fn into_type(self) -> Option<T>;
}

/// Automatically implement `From` and `AsType` for an enum variant.
/// Example:
/// ```
/// use safecast::as_type;
///
/// struct Bar;
///
/// enum Foo {
///     Bar(Bar),
/// }
///
/// as_type!(Foo, Bar, Bar);
/// ```
#[macro_export]
macro_rules! as_type {
    ($c:ident<$($cg:tt),*>, $variant:ident, $t:ty) => {
        impl<$($cg),+> From<$t> for $c<$($cg),+> {
            fn from(t: $t) -> Self {
                Self::$variant(t)
            }
        }

        impl<$($cg),+> $crate::AsType<$t> for $c<$($cg),+> {
            fn as_type(&self) -> Option<&$t> {
                match self {
                    Self::$variant(variant) => Some(variant),
                    _ => None,
                }
            }

            fn as_type_mut(&mut self) -> Option<&mut $t> {
                match self {
                    Self::$variant(variant) => Some(variant),
                    _ => None,
                }
            }

            fn into_type(self) -> Option<$t> {
                match self {
                    Self::$variant(variant) => Some(variant),
                    _ => None,
                }
            }
        }
    };
    ($c:ty, $variant:ident, $t:ty) => {
        impl From<$t> for $c {
            fn from(t: $t) -> Self {
                Self::$variant(t)
            }
        }

        impl $crate::AsType<$t> for $c {
            fn as_type(&self) -> Option<&$t> {
                match self {
                    Self::$variant(variant) => Some(variant),
                    _ => None,
                }
            }

            fn as_type_mut(&mut self) -> Option<&mut $t> {
                match self {
                    Self::$variant(variant) => Some(variant),
                    _ => None,
                }
            }

            fn into_type(self) -> Option<$t> {
                match self {
                    Self::$variant(variant) => Some(variant),
                    _ => None,
                }
            }
        }
    };
}

/// Trait for defining a cast operation from some source type `T`.
/// Analogous to [`From`].
/// The inverse of [`CastInto`].
/// Prefer implementing `CastFrom` over `CastInto` because implementing `CastFrom` automatically
/// provides an implementation of `CastInto`.
pub trait CastFrom<T> {
    /// Cast an instance of `T` into an instance of `Self`.
    fn cast_from(value: T) -> Self;
}

/// Trait for defining a cast operation to some destination type `T`.
/// Analogous to [`Into`].
/// The inverse of [`CastFrom`].
/// Prefer implementing `CastFrom` over `CastInto` because implementing `CastFrom` automatically
/// provides an implementation of `CastInto`.
pub trait CastInto<T> {
    /// Cast an instance of `Self` into an instance of `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,
    }

    #[allow(dead_code)]
    enum FooBar {
        Foo(Foo),
        Bar(Bar),
        Baz(Baz),
    }

    as_type!(FooBar, 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());
    }

    #[test]
    fn test_as_type_macro() {
        let bar = Bar { b: 0 };
        let foo_bar = FooBar::Bar(bar);
        assert_eq!(foo_bar.as_type(), Some(&bar));
    }
}