message_history.rs

 1pub struct MessageHistory<T> {
 2    items: Vec<T>,
 3    current: Option<usize>,
 4}
 5
 6impl<T> Default for MessageHistory<T> {
 7    fn default() -> Self {
 8        MessageHistory {
 9            items: Vec::new(),
10            current: None,
11        }
12    }
13}
14
15impl<T> MessageHistory<T> {
16    pub fn push(&mut self, message: T) {
17        self.current.take();
18        self.items.push(message);
19    }
20
21    pub fn reset_position(&mut self) {
22        self.current.take();
23    }
24
25    pub fn prev(&mut self) -> Option<&T> {
26        if self.items.is_empty() {
27            return None;
28        }
29
30        let new_ix = self
31            .current
32            .get_or_insert(self.items.len())
33            .saturating_sub(1);
34
35        self.current = Some(new_ix);
36        self.items.get(new_ix)
37    }
38
39    pub fn next(&mut self) -> Option<&T> {
40        let current = self.current.as_mut()?;
41        *current += 1;
42
43        self.items.get(*current).or_else(|| {
44            self.current.take();
45            None
46        })
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    #[test]
55    fn test_prev_next() {
56        let mut history = MessageHistory::default();
57
58        // Test empty history
59        assert_eq!(history.prev(), None);
60        assert_eq!(history.next(), None);
61
62        // Add some messages
63        history.push("first");
64        history.push("second");
65        history.push("third");
66
67        // Test prev navigation
68        assert_eq!(history.prev(), Some(&"third"));
69        assert_eq!(history.prev(), Some(&"second"));
70        assert_eq!(history.prev(), Some(&"first"));
71        assert_eq!(history.prev(), Some(&"first"));
72
73        assert_eq!(history.next(), Some(&"second"));
74
75        // Test mixed navigation
76        history.push("fourth");
77        assert_eq!(history.prev(), Some(&"fourth"));
78        assert_eq!(history.prev(), Some(&"third"));
79        assert_eq!(history.next(), Some(&"fourth"));
80        assert_eq!(history.next(), None);
81
82        // Test that push resets navigation
83        history.prev();
84        history.prev();
85        history.push("fifth");
86        assert_eq!(history.prev(), Some(&"fifth"));
87    }
88}