Skip to content

Instantly share code, notes, and snippets.

@njam
Created November 3, 2019 16:09
Show Gist options
  • Save njam/cb8ba921465b15b5a5aa2df695e8caf7 to your computer and use it in GitHub Desktop.
Save njam/cb8ba921465b15b5a5aa2df695e8caf7 to your computer and use it in GitHub Desktop.
#[test]
fn filter_signal_cloned() {
let list = signal_vec::always(vec![3, 1, 6, 2]).map(Rc::new);
#[derive(Copy, Clone)]
enum FilterOption { Odd, Even }
let filter_option = Rc::new(Mutable::new(FilterOption::Odd));
let mut signal = list
.filter_signal_cloned(|item| {
let item = Rc::clone(item);
let filter_option = Rc::clone(&filter_option);
filter_option.signal_ref(move |filter_option| {
match filter_option {
FilterOption::Odd => *item % 2 != 0,
FilterOption::Even => *item % 2 == 0,
}
})
});
let mut diffs = move || {
block_on(poll_fn(|context| {
let mut output = Vec::new();
loop {
let poll = Pin::new(&mut signal).poll_vec_change(context);
return match poll {
Poll::Ready(Some(item)) => {
output.push(item);
continue;
}
_ => {
Poll::Ready(output)
}
};
}
}))
};
assert_eq!(diffs(), vec!(
VecDiff::Replace { values: vec![Rc::new(3), Rc::new(1)] },
));
filter_option.set(FilterOption::Even);
assert_eq!(diffs(), vec!(
VecDiff::RemoveAt { index: 0 },
VecDiff::RemoveAt { index: 0 },
VecDiff::InsertAt { index: 0, value: Rc::new(6) },
VecDiff::InsertAt { index: 1, value: Rc::new(2) },
));
}
#[test]
fn sort_by_cloned() {
let list = signal_vec::always(vec![3, 1, 6, 2]).map(Rc::new);
#[derive(Copy, Clone)]
enum SortOption { Incr, Decr }
let sort_option = Rc::new(Mutable::new(SortOption::Incr));
let mut signal = list
.sort_by_cloned({
let sort_option = Rc::clone(&sort_option);
move |left, right| {
match sort_option.get() {
SortOption::Incr => left.cmp(&right),
SortOption::Decr => right.cmp(&left),
}
}
});
let mut diffs = move || {
block_on(poll_fn(|context| {
let mut output = Vec::new();
loop {
let poll = Pin::new(&mut signal).poll_vec_change(context);
return match poll {
Poll::Ready(Some(item)) => {
output.push(item);
continue;
}
_ => {
Poll::Ready(output)
}
};
}
}))
};
assert_eq!(diffs(), vec!(
VecDiff::Replace { values: vec![Rc::new(1), Rc::new(2), Rc::new(3), Rc::new(6)] },
));
sort_option.set(SortOption::Decr);
assert_eq!(diffs(), vec!());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment