Struct TypeCache

Source
pub struct TypeCache { /* private fields */ }
Expand description

The TypeCache is heavily inspired by the state crate and the way the Rocket framework handles global and local state. You could say we’ve immutably borrowed some ideas. Rim-shot!

Basically, we’ve got a hash that can store different types but only one of each type. The type id is the key, and you need to know what type you’re asking for when you call get() to be able to do anything with it:

let cache = TypeCache::new();

cache.set::<String>("Hi friends".to_string());
assert_eq!(Some(&"Hi friends".to_string()), cache.get::<String>());

cache.set::<usize>(12345);
assert_eq!(Some(&12345), cache.get::<usize>());

We use this in Vial for global state as well as local request state, however this design is flawed as the local cache shouldn’t be forced into Send + Sync. These two will be separated in a future release.

Implementations§

Source§

impl TypeCache

Source

pub fn new() -> TypeCache

Create a new, empty TypeCache.

Source

pub fn get<T: Send + Sync + 'static>(&self) -> Option<&T>

TypeCache works like a regular hash map, but with types as keys. Meaning it can only store one of each type. Choose wisely.

Source

pub fn set<T: Send + Sync + 'static>(&self, v: T)

As long as your object is Send + Sync + 'static, TypeCache can store it.

Trait Implementations§

Source§

impl Debug for TypeCache

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for TypeCache

Source§

fn default() -> TypeCache

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.