Skip to content

react: example: Check all dependents to avoid partial write #203

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 17, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions exercises/react/example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,14 @@ impl <'a, T: Copy + PartialEq> Reactor<'a, T> {
}

pub fn create_compute<F: Fn(&[T]) -> T + 'a>(&mut self, dependencies: &[CellID], compute_func: F) -> Result<CellID, &'static str> {
// Check all dependencies' validity before modifying any of them,
// so that we don't perform an incorrect partial write.
if !dependencies.iter().all(|&id| id < self.cells.len()) {
return Err("Nonexistent input");
}
let new_id = self.cells.len();
for &id in dependencies {
match self.cells.get_mut(id) {
Some(c) => c.dependents.push(new_id),
None => return Err("Nonexistent input"),
}
self.cells.get_mut(id).unwrap().dependents.push(new_id);
}
let inputs: Vec<_> = dependencies.iter().map(|&id| self.value(id).unwrap()).collect();
let initial = compute_func(&inputs);
Expand Down
13 changes: 13 additions & 0 deletions exercises/react/tests/react.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,19 @@ fn error_creating_compute_cell_if_input_doesnt_exist() {
assert!(Reactor::new().create_compute(&vec![input], |_| 0).is_err());
}

#[test]
#[ignore]
fn do_not_break_cell_if_creating_compute_cell_with_valid_and_invalid_input() {
let mut dummy_reactor = Reactor::new();
let _ = dummy_reactor.create_input(1);
let dummy_cell = dummy_reactor.create_input(2);
let mut reactor = Reactor::new();
let input = reactor.create_input(1);
assert!(reactor.create_compute(&vec![input, dummy_cell], |_| 0).is_err());
assert!(reactor.set_value(input, 5).is_ok());
assert_eq!(reactor.value(input).unwrap(), 5);
}

#[test]
#[ignore]
fn compute_cells_update_value_when_dependencies_are_changed() {
Expand Down