Skip to content

Commit

Permalink
Fix Events::<drain/clear> bug
Browse files Browse the repository at this point in the history
Co-authored-by: Alice Cecile <[email protected]>
  • Loading branch information
NathanSWard and alice-i-cecile committed May 18, 2021
1 parent d4ffa3f commit 8b1abbb
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions crates/bevy_ecs/src/event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -328,14 +328,25 @@ impl<T: Component> Events<T> {
events.update();
}

#[inline]
fn increment_start_event_count(&mut self) {
let count = self.event_count + 1;
self.a_start_event_count = count;
self.b_start_event_count = count;
}

/// Removes all events.
#[inline]
pub fn clear(&mut self) {
self.increment_start_event_count();
self.events_a.clear();
self.events_b.clear();
}

/// Creates a draining iterator that removes all events.
pub fn drain(&mut self) -> impl Iterator<Item = T> + '_ {
self.increment_start_event_count();

let map = |i: EventInstance<T>| i.event;
match self.state {
State::A => self
Expand Down Expand Up @@ -480,4 +491,40 @@ mod tests {
) -> Vec<TestEvent> {
reader.iter(events).cloned().collect::<Vec<TestEvent>>()
}

#[derive(PartialEq, Eq, Debug)]
struct E(usize);

fn events_clear_and_read_impl(clear_func: impl FnOnce(&mut Events<E>)) {
let mut events = Events::<E>::default();
let mut reader = events.get_reader();

assert!(reader.iter(&events).next().is_none());

events.send(E(0));
assert_eq!(*reader.iter(&events).next().unwrap(), E(0));
assert_eq!(reader.iter(&events).next(), None);

events.send(E(1));
clear_func(&mut events);
assert!(reader.iter(&events).next().is_none());

events.send(E(2));
events.update();
events.send(E(3));

assert!(reader.iter(&events).eq([E(2), E(3)].iter()));
}

#[test]
fn test_events_clear_and_read() {
events_clear_and_read_impl(|events| events.clear());
}

#[test]
fn test_events_drain_and_read() {
events_clear_and_read_impl(|events| {
assert!(events.drain().eq(vec![E(0), E(1)].into_iter()));
});
}
}

0 comments on commit 8b1abbb

Please sign in to comment.