Implementation of user data in cursive::Cursive
(Jin Qing's Column, Oct., 2022)
cursive::Cursive can store any user data:
pub struct Cursive {
...
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();
siv.set_user_data(vec![1i32, 2, 3]);
assert_eq!(siv.user_data::<Vec<i32>>(), Some(&mut vec![1i32, 2, 3]));
siv.with_user_data(|numbers: &mut Vec<i32>| numbers.push(4));
let data: Vec<i32> = siv.take_user_data().unwrap();
assert_eq!(data, vec![1i32, 2, 3, 4]);
assert_eq!(siv.user_data::<Vec<i32>>(), None);