From a4ae92c083ae4b195b7e4d39e957e0a4becdeaa8 Mon Sep 17 00:00:00 2001 From: torkleyy Date: Sat, 2 Sep 2017 11:57:27 +0200 Subject: [PATCH] Add optional fetching of resources --- Cargo.toml | 6 +++--- examples/fetch_opt.rs | 45 +++++++++++++++++++++++++++++++++++++++++++ src/res.rs | 32 ++++++++++++++++++++++++++++++ 3 files changed, 80 insertions(+), 3 deletions(-) create mode 100644 examples/fetch_opt.rs diff --git a/Cargo.toml b/Cargo.toml index 412068b..82e8078 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "shred" -version = "0.4.3" -authors = ["torkleyy"] +version = "0.4.4" +authors = ["torkleyy "] description = """ Dispatches systems in parallel which need read access to some resources, and write access to others. @@ -27,4 +27,4 @@ shred-derive = { path = "shred-derive", version = "0.3" } smallvec = "0.4" [dev-dependencies] -cgmath = "0.14" +cgmath = "0.15" diff --git a/examples/fetch_opt.rs b/examples/fetch_opt.rs new file mode 100644 index 0000000..57eb4e2 --- /dev/null +++ b/examples/fetch_opt.rs @@ -0,0 +1,45 @@ +extern crate shred; + +use shred::{DispatcherBuilder, Fetch, FetchMut, Resources, System}; + +#[derive(Debug)] +struct ResA; + +#[derive(Debug)] +struct ResB; + +struct PrintSystem; + +impl<'a> System<'a> for PrintSystem { + // We can simply use `Option` or `Option` if a resource + // isn't strictly required. + type SystemData = (Fetch<'a, ResA>, Option>); + + fn run(&mut self, data: Self::SystemData) { + let (a, mut b) = data; + + println!("{:?}", &*a); + + if let Some(ref mut x) = b { + println!("{:?}", &**x); + + **x = ResB; + } + } +} + +fn main() { + let mut resources = Resources::new(); + let mut dispatcher = DispatcherBuilder::new() + .add(PrintSystem, "print", &[]) // Adds a system "print" without dependencies + .build(); + resources.add(ResA); + + // `ResB` is not in resources, but `PrintSystem` still works. + dispatcher.dispatch(&mut resources); + + resources.add(ResB); + + // Now `ResB` can be printed, too. + dispatcher.dispatch(&mut resources); +} diff --git a/src/res.rs b/src/res.rs index 7de2cae..7b7f565 100644 --- a/src/res.rs +++ b/src/res.rs @@ -124,6 +124,38 @@ impl<'a, T> SystemData<'a> for FetchMut<'a, T> } } +impl<'a, T> SystemData<'a> for Option> + where T: Resource +{ + fn fetch(res: &'a Resources, id: usize) -> Self { + res.try_fetch(id) + } + + fn reads(id: usize) -> Vec { + vec![ResourceId::new_with_id::(id)] + } + + fn writes(_: usize) -> Vec { + vec![] + } +} + +impl<'a, T> SystemData<'a> for Option> + where T: Resource +{ + fn fetch(res: &'a Resources, id: usize) -> Self { + res.try_fetch_mut(id) + } + + fn reads(_: usize) -> Vec { + vec![] + } + + fn writes(id: usize) -> Vec { + vec![ResourceId::new_with_id::(id)] + } +} + /// A resource defines a set of data /// which can only be accessed according /// to Rust's typical borrowing model (one writer xor multiple readers).