//! Bookmarks, kept on this device only. No account, no sync. use alloc::string::{String, ToString}; use alloc::vec::Vec; #[derive(Clone, Debug, PartialEq, Eq)] pub struct Bookmark { pub title: String, pub url: String, } #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct Bookmarks { pub items: Vec, } impl Bookmarks { pub fn contains(&self, url: &str) -> bool { self.items.iter().any(|b| b.url == url) } /// Add the page, or remove it when it is already saved. Returns true /// when the page is saved afterwards. pub fn toggle(&mut self, url: &str, title: &str) -> bool { if let Some(i) = self.items.iter().position(|b| b.url == url) { self.items.remove(i); false } else { let title = if title.trim().is_empty() { url } else { title.trim() }; self.items.push(Bookmark { title: title.to_string(), url: url.to_string() }); true } } pub fn remove(&mut self, url: &str) { self.items.retain(|b| b.url != url); } /// One bookmark per line: address, a tab, then the title. pub fn to_text(&self) -> String { let mut s = String::new(); for b in &self.items { s.push_str(&b.url); s.push('\t'); s.push_str(&b.title.replace(['\t', '\n'], " ")); s.push('\n'); } s } pub fn from_text(text: &str) -> Bookmarks { let items = text .lines() .filter_map(|l| { let mut p = l.splitn(2, '\t'); let url = p.next()?.trim(); if url.is_empty() { return None; } let title = p.next().unwrap_or(url).trim(); Some(Bookmark { title: title.to_string(), url: url.to_string() }) }) .collect(); Bookmarks { items } } } #[cfg(test)] mod tests { use super::*; #[test] fn round_trip() { let mut b = Bookmarks::default(); assert!(b.toggle("https://a.example/", "A\tpage")); assert!(b.toggle("https://b.example/", "")); let back = Bookmarks::from_text(&b.to_text()); assert_eq!(back.items[0].title, "A page"); assert_eq!(back.items[1].title, "https://b.example/"); assert!(!b.toggle("https://a.example/", "A")); assert!(!b.contains("https://a.example/")); } }