//! Back and forward. use alloc::string::String; use alloc::vec::Vec; #[derive(Default, Clone, Debug)] pub struct History { back: Vec, current: Option, forward: Vec, } impl History { /// A new page was opened by the person (not back or forward). pub fn visit(&mut self, url: String) { if self.current.as_deref() == Some(url.as_str()) { return; } if let Some(c) = self.current.take() { self.back.push(c); if self.back.len() > 500 { self.back.remove(0); } } self.current = Some(url); self.forward.clear(); } /// After a redirect, the page that opened has a different address. pub fn replace(&mut self, url: String) { self.current = Some(url); } pub fn current(&self) -> Option<&str> { self.current.as_deref() } pub fn can_back(&self) -> bool { !self.back.is_empty() } pub fn can_forward(&self) -> bool { !self.forward.is_empty() } pub fn back(&mut self) -> Option { let prev = self.back.pop()?; if let Some(c) = self.current.replace(prev.clone()) { self.forward.push(c); } Some(prev) } pub fn forward(&mut self) -> Option { let next = self.forward.pop()?; if let Some(c) = self.current.replace(next.clone()) { self.back.push(c); } Some(next) } } #[cfg(test)] mod tests { use super::*; #[test] fn back_and_forward() { let mut h = History::default(); h.visit("a".into()); h.visit("b".into()); h.visit("c".into()); assert_eq!(h.back().as_deref(), Some("b")); assert_eq!(h.back().as_deref(), Some("a")); assert!(h.back().is_none()); assert_eq!(h.forward().as_deref(), Some("b")); h.visit("d".into()); assert!(!h.can_forward()); assert_eq!(h.current(), Some("d")); } }