pub enum Entry<'a, K: 'a, V: 'a> {
Occupied(OccupiedEntry<K, V>),
Vacant(VacantEntry<'a, K, V>),
}Expand description
A view into a single entry in a cache, which may either be vacant or occupied.
This enum is constructed from the entry method on Cache.
Variants§
Implementations§
Source§impl<'a, K, V> Entry<'a, K, V>
impl<'a, K, V> Entry<'a, K, V>
Sourcepub fn or_insert(self, default: V) -> V
pub fn or_insert(self, default: V) -> V
Ensures a value is in the entry by inserting the default if empty, and returns a copy of the value in the entry.
Examples
use cache_cache::Cache;
let mut target_positions = Cache::keep_last();
target_positions.entry(10).or_insert(0);
assert_eq!(target_positions[&10], 0);Sourcepub fn or_insert_with<F: FnOnce(&K) -> V>(self, default: F) -> V
pub fn or_insert_with<F: FnOnce(&K) -> V>(self, default: F) -> V
Ensures a value is in the entry by inserting the result of the default function if empty, and returns a copy of the value in the entry.
In contrary to HashMap API, the default function takes the key as argument. As shown in the example, it makes the IO call simpler. It does require the key to implement the Copy trait though.
Examples
use cache_cache::Cache;
let mut torque_enable: Cache<u8, bool> = Cache::keep_last();
torque_enable.entry(20).or_insert_with(|id| false);
assert_eq!(torque_enable[&20], false);Sourcepub fn or_try_insert_with<F: FnOnce(&K) -> Result<V, Box<dyn Error>>>(
self,
default: F,
) -> Result<V, Box<dyn Error>>
pub fn or_try_insert_with<F: FnOnce(&K) -> Result<V, Box<dyn Error>>>( self, default: F, ) -> Result<V, Box<dyn Error>>
Tries inserting a value in the entry (if empty) with the default function and returns a Result of the value in the entry or the error encounter by the default function.
Examples
use cache_cache::Cache;
use std::{error::Error, fmt};
#[derive(Debug)]
struct MyDummyIOError;
impl fmt::Display for MyDummyIOError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "my io error")
}
}
impl Error for MyDummyIOError {}
fn enable_torque(id: &u8) -> Result<bool, Box<dyn Error>> {
// Send hardware command that could fail, something like
// serial_send_torque_on_command(...)?;
// For example purposes, we suppose here that our method:
// * will work for id within 0...10
// * fail for other
if *id > 10 {
Err(Box::new(MyDummyIOError))
}
else {
Ok(true)
}
}
let mut torque_enable = Cache::keep_last();
let res = torque_enable.entry(5).or_try_insert_with(enable_torque);
assert!(res.is_ok());
assert_eq!(res.unwrap(), true);
let res = torque_enable.entry(20).or_try_insert_with(enable_torque);
assert!(res.is_err());