Skip to content

Commit

Permalink
Merge #49
Browse files Browse the repository at this point in the history
49: Add optional fetching of resources r=torkleyy a=torkleyy

cc @Rhuagh
  • Loading branch information
bors[bot] committed Sep 2, 2017
2 parents db43c75 + a4ae92c commit b0f4489
Show file tree
Hide file tree
Showing 3 changed files with 80 additions and 3 deletions.
6 changes: 3 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[package]
name = "shred"
version = "0.4.3"
authors = ["torkleyy"]
version = "0.4.4"
authors = ["torkleyy <[email protected]>"]
description = """
Dispatches systems in parallel which need read access to some resources,
and write access to others.
Expand All @@ -27,4 +27,4 @@ shred-derive = { path = "shred-derive", version = "0.3" }
smallvec = "0.4"

[dev-dependencies]
cgmath = "0.14"
cgmath = "0.15"
45 changes: 45 additions & 0 deletions examples/fetch_opt.rs
Original file line number Diff line number Diff line change
@@ -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<Fetch>` or `Option<FetchMut>` if a resource
// isn't strictly required.
type SystemData = (Fetch<'a, ResA>, Option<FetchMut<'a, ResB>>);

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);
}
32 changes: 32 additions & 0 deletions src/res.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,38 @@ impl<'a, T> SystemData<'a> for FetchMut<'a, T>
}
}

impl<'a, T> SystemData<'a> for Option<Fetch<'a, T>>
where T: Resource
{
fn fetch(res: &'a Resources, id: usize) -> Self {
res.try_fetch(id)
}

fn reads(id: usize) -> Vec<ResourceId> {
vec![ResourceId::new_with_id::<T>(id)]
}

fn writes(_: usize) -> Vec<ResourceId> {
vec![]
}
}

impl<'a, T> SystemData<'a> for Option<FetchMut<'a, T>>
where T: Resource
{
fn fetch(res: &'a Resources, id: usize) -> Self {
res.try_fetch_mut(id)
}

fn reads(_: usize) -> Vec<ResourceId> {
vec![]
}

fn writes(id: usize) -> Vec<ResourceId> {
vec![ResourceId::new_with_id::<T>(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).
Expand Down

0 comments on commit b0f4489

Please sign in to comment.