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#[cfg(test)]
50mod tests {
51    use super::*;
52
53    #[test]
54    fn test_prev_next() {
55        let mut history = MessageHistory::default();
56
57        // Test empty history
58        assert_eq!(history.prev(), None);
59        assert_eq!(history.next(), None);
60
61        // Add some messages
62        history.push("first");
63        history.push("second");
64        history.push("third");
65
66        // Test prev navigation
67        assert_eq!(history.prev(), Some(&"third"));
68        assert_eq!(history.prev(), Some(&"second"));
69        assert_eq!(history.prev(), Some(&"first"));
70        assert_eq!(history.prev(), Some(&"first"));
71
72        assert_eq!(history.next(), Some(&"second"));
73
74        // Test mixed navigation
75        history.push("fourth");
76        assert_eq!(history.prev(), Some(&"fourth"));
77        assert_eq!(history.prev(), Some(&"third"));
78        assert_eq!(history.next(), Some(&"fourth"));
79        assert_eq!(history.next(), None);
80
81        // Test that push resets navigation
82        history.prev();
83        history.prev();
84        history.push("fifth");
85        assert_eq!(history.prev(), Some(&"fifth"));
86    }
87}