Add mutator

This commit is contained in:
Sasha Pourcelot 2021-08-24 14:56:54 +02:00
parent 1aa796f253
commit e11b3170e9
3 changed files with 22 additions and 7 deletions

View File

@ -6,11 +6,12 @@ async fn child_task(ctx: BastionContext) -> Result<(), ()> {
loop {
MessageHandler::new(ctx.recv().await?)
.on_tell(|_: DummyMessage, _| {
ctx.read_data(|child_usize: Option<&usize>| {
let child_usize = child_usize.unwrap();
println!("My state says my usize is `{}`", child_usize);
})
ctx.write_data(|value| {
value.map(|v: &usize| {
println!("My counter is at `{}`. Let's increment it!", v);
v + 1
})
});
})
.on_fallback(|_, _| panic!("Unhandled message"));
}
@ -19,6 +20,10 @@ async fn child_task(ctx: BastionContext) -> Result<(), ()> {
#[derive(Debug)]
struct DummyMessage;
// $ cargo r --example with_data
// My counter is at `42`. Let's increment it!
// My counter is at `43`. Let's increment it!
// My counter is at `44`. Let's increment it!
fn main() {
env_logger::init();
@ -30,6 +35,8 @@ fn main() {
let child = &children.elems()[0];
child.tell_anonymously(DummyMessage).unwrap();
child.tell_anonymously(DummyMessage).unwrap();
child.tell_anonymously(DummyMessage).unwrap();
thread::sleep(Duration::from_secs(1));

View File

@ -778,6 +778,14 @@ impl BastionContext {
pub fn read_data<T: Send + Sync + 'static, O>(&self, f: impl FnOnce(Option<&T>) -> O) -> O {
self.state.data.read(|t| f(t))
}
// TODO(scrabsha): add doc, document same type collision
pub fn write_data<T: std::fmt::Debug + Send + Sync + 'static>(
&self,
f: impl FnOnce(Option<&T>) -> Option<T>,
) {
self.state.data.write(f)
}
}
impl ContextState {

View File

@ -54,9 +54,9 @@ impl GlobalState {
}
/// Invokes a function with the requested data type.
pub fn write<T: std::fmt::Debug + Send + Sync + 'static, F>(&mut self, f: F)
pub fn write<T: std::fmt::Debug + Send + Sync + 'static, F>(&self, f: F)
where
F: Fn(Option<&T>) -> Option<T>,
F: FnOnce(Option<&T>) -> Option<T>,
{
let mut hm = self.table.write().unwrap();
let stuff_to_insert = match hm.entry(TypeId::of::<T>()) {