try_as_traits/
lib.rs

1//! Contains the traits `TryAsRef`, `TryAsMut` and `TypedContainer`, used by the crate [try_as](https://crates.io/crates/try_as) to simplfy dealing with enums enumerating types.
2//!
3//! See the the [crate documentation](https://nearoo.github.io/try_as/try_as/) for more information
4//! and documentation on how to use the traits.
5
6use std::any::TypeId;
7
8/// A version of `AsRef<T>` that can fail.
9pub trait TryAsRef<T> {
10    fn try_as_ref(&self) -> Option<&T>;
11}
12
13/// A version of `AsMut<T>` that can fail.
14pub trait TryAsMut<T> {
15    fn try_as_mut(&mut self) -> Option<&mut T>;
16}
17
18/// A trait for types that can hold values of different types.
19pub trait TypedContainer {
20    /// Returns `true` excactly if the type of the contained vlaue is `T`.
21    fn holds<T: 'static>(&self) -> bool {
22        TypeId::of::<T>() == self.type_id()
23    }
24
25    /// Returns the [`std::any::TypeId`] of the contained value.
26    fn type_id(&self) -> TypeId;
27}