Implementation of user data in cursive::Cursive
(Jin Qing’s Column, Oct., 2022)
cursive::Cursive can store any user data:
pub struct Cursive {
...
// User-provided data.
user_data: Box<dyn Any>,
}
impl Cursive {
...
pub fn set_user_data<T: Any>(&mut self, user_data: T) {
self.user_data = Box::new(user_data);
}
pub fn user_data<T: Any>(&mut self) -> Option<&mut T> {
self.user_data.downcast_mut()
}
pub fn take_user_data<T: Any>(&mut self) -> Option<T> {
...
}
pub fn with_user_data<F, T, R>(&mut self, f: F) -> Option<R>
where
F: FnOnce(&mut T) -> R,
T: Any,
{
self.user_data().map(f)
}
Example:
let mut siv = cursive_core::Cursive::new();
// Start with a simple `Vec<i32>` as user data.
siv.set_user_data(vec![1i32, 2, 3]);
assert_eq!(siv.user_data::<Vec<i32>>(), Some(&mut vec![1i32, 2, 3]));
// Let's mutate the data a bit.
siv.with_user_data(|numbers: &mut Vec<i32>| numbers.push(4));
// If mutable reference is not enough, we can take the data by value.
let data: Vec<i32> = siv.take_user_data().unwrap();
assert_eq!(data, vec![1i32, 2, 3, 4]);
// At this point the user data was removed and is no longer available.
assert_eq!(siv.user_data::<Vec<i32>>(), None);