Skip to main content

use_event_stream/
lib.rs

1#![forbid(unsafe_code)]
2#![doc = include_str!("../README.md")]
3
4#[derive(Clone, Debug, Default, Eq, PartialEq)]
5pub struct EventStream<E> {
6    events: Vec<E>,
7}
8
9impl<E> EventStream<E> {
10    pub const fn new() -> Self {
11        Self { events: Vec::new() }
12    }
13
14    pub const fn from_events(events: Vec<E>) -> Self {
15        Self { events }
16    }
17
18    pub fn push(&mut self, event: E) {
19        self.events.push(event);
20    }
21
22    pub fn iter(&self) -> core::slice::Iter<'_, E> {
23        self.events.iter()
24    }
25
26    pub fn len(&self) -> usize {
27        self.events.len()
28    }
29
30    pub fn is_empty(&self) -> bool {
31        self.events.is_empty()
32    }
33}
34
35impl<'a, E> IntoIterator for &'a EventStream<E> {
36    type Item = &'a E;
37    type IntoIter = core::slice::Iter<'a, E>;
38
39    fn into_iter(self) -> Self::IntoIter {
40        self.iter()
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::EventStream;
47
48    #[test]
49    fn pushes_and_iterates_events() {
50        let mut stream = EventStream::new();
51        stream.push("command.started");
52        stream.push("command.finished");
53
54        let events = stream.iter().copied().collect::<Vec<_>>();
55
56        assert_eq!(events, ["command.started", "command.finished"]);
57        assert_eq!(stream.len(), 2);
58    }
59
60    #[test]
61    fn builds_from_existing_events() {
62        let stream = EventStream::from_events(vec!["a", "b"]);
63
64        assert!(!stream.is_empty());
65        assert_eq!(stream.len(), 2);
66    }
67}