BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / emoji / recent.rs

recent.rs

b2f76237 History
recent.rs 1.9 KiB Download Raw
1const LIMIT: usize = 24;
2const META_KEY: &str = "emoji_recent";
3const TEAMS_QUICK_REACTIONS: [&str; 6] = ["👍", "❤️", "😆", "😮", "😢", "😡"];
4
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct Recent(Vec<String>);
7
8impl Default for Recent {
9 fn default() -> Self {
10 Recent(TEAMS_QUICK_REACTIONS.map(str::to_owned).to_vec())
11 }
12}
13
14impl Recent {
15 pub fn load(store: &store::Store) -> Self {
16 match store.meta(META_KEY) {
17 Ok(Some(stored)) => Self::parse(&stored),
18 _ => Self::default(),
19 }
20 }
21
22 pub fn save(&self, store: &store::Store) {
23 store.set_meta(META_KEY, &self.0.join("\n")).ok();
24 }
25
26 fn parse(stored: &str) -> Self {
27 Recent(
28 stored
29 .lines()
30 .filter(|glyph| !glyph.is_empty())
31 .take(LIMIT)
32 .map(str::to_owned)
33 .collect(),
34 )
35 }
36
37 pub fn glyphs(&self) -> &[String] {
38 &self.0
39 }
40
41 pub fn push(&mut self, glyph: &str) {
42 self.0.retain(|known| known != glyph);
43 self.0.insert(0, glyph.to_owned());
44 self.0.truncate(LIMIT);
45 }
46}
47
48#[cfg(test)]
49mod tests {
50 use super::{LIMIT, Recent};
51
52 #[test]
53 fn starts_with_the_teams_quick_reactions() {
54 assert_eq!(Recent::default().glyphs()[..2], ["👍", "❤️"]);
55 }
56
57 #[test]
58 fn newest_first_without_duplicates() {
59 let mut recent = Recent::parse("");
60 recent.push("👍");
61 recent.push("❤️");
62 recent.push("👍");
63 assert_eq!(recent.glyphs(), ["👍", "❤️"]);
64 }
65
66 #[test]
67 fn keeps_at_most_the_limit() {
68 let mut recent = Recent::parse("");
69 for index in 0..LIMIT + 5 {
70 recent.push(&index.to_string());
71 }
72 assert_eq!(recent.glyphs().len(), LIMIT);
73 assert_eq!(Recent::parse(&recent.glyphs().join("\n")), recent);
74 }
75}