1use std::collections::HashMap;
7
8const HALF_LIFE_DAYS: f64 = 14.0;
10const FULL_BOOST_USES: f64 = 20.0;
12const MAX_ENTRIES: usize = 512;
14const SECONDS_PER_DAY: f64 = 86_400.0;
15
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17struct Entry {
18 count: u32,
19 last: u64,
20}
21
22#[derive(Clone, Debug, Default, PartialEq, Eq)]
26pub struct Frecency {
27 entries: HashMap<String, Entry>,
28}
29
30impl Frecency {
31 pub fn record(&mut self, id: &str, now: u64) {
33 let entry = self.entries.entry(id.to_owned()).or_insert(Entry {
34 count: 0,
35 last: now,
36 });
37 entry.count = entry.count.saturating_add(1);
38 entry.last = entry.last.max(now);
39 if self.entries.len() > MAX_ENTRIES {
40 self.prune(now);
41 }
42 }
43
44 fn prune(&mut self, now: u64) {
45 let mut weights: Vec<(String, f64)> = self
46 .entries
47 .iter()
48 .map(|(id, entry)| (id.clone(), weight(*entry, now)))
49 .collect();
50 weights.sort_by(|a, b| b.1.total_cmp(&a.1));
51 for (id, _) in weights.into_iter().skip(MAX_ENTRIES) {
52 self.entries.remove(&id);
53 }
54 }
55
56 #[must_use]
58 pub fn boost(&self, id: &str, now: u64, max: i32) -> i32 {
59 let Some(entry) = self.entries.get(id) else {
60 return 0;
61 };
62 let full = (1.0 + FULL_BOOST_USES).ln();
63 let share = (weight(*entry, now) / full).clamp(0.0, 1.0);
64 #[allow(
65 clippy::cast_possible_truncation,
66 reason = "a share in 0..=1 of a small integer"
67 )]
68 let boost = (share * f64::from(max)).ceil() as i32;
69 boost.clamp(0, max)
70 }
71
72 #[must_use]
75 pub fn share(&self, id: &str, now: u64) -> f32 {
76 let Some(entry) = self.entries.get(id) else {
77 return 0.0;
78 };
79 let full = (1.0 + FULL_BOOST_USES).ln();
80 #[allow(
81 clippy::cast_possible_truncation,
82 reason = "a share in 0..=1 needs no more than f32"
83 )]
84 let share = (weight(*entry, now) / full).clamp(0.0, 1.0) as f32;
85 share
86 }
87
88 #[must_use]
90 pub fn most_recent(&self, limit: usize) -> Vec<&str> {
91 let mut entries: Vec<(&str, u64)> = self
92 .entries
93 .iter()
94 .map(|(id, entry)| (id.as_str(), entry.last))
95 .collect();
96 entries.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(b.0)));
97 entries.into_iter().take(limit).map(|(id, _)| id).collect()
98 }
99
100 #[must_use]
102 pub fn last_used(&self, id: &str) -> Option<u64> {
103 self.entries.get(id).map(|entry| entry.last)
104 }
105
106 #[must_use]
108 pub fn serialize(&self) -> String {
109 let mut lines: Vec<String> = self
110 .entries
111 .iter()
112 .map(|(id, entry)| format!("{id}\t{}\t{}", entry.count, entry.last))
113 .collect();
114 lines.sort();
115 let mut text = lines.join("\n");
116 text.push('\n');
117 text
118 }
119
120 #[must_use]
122 pub fn parse(text: &str) -> Self {
123 let entries = text
124 .lines()
125 .filter_map(|line| {
126 let mut parts = line.split('\t');
127 let id = parts.next().filter(|id| !id.is_empty())?;
128 let count = parts.next()?.parse().ok()?;
129 let last = parts.next()?.parse().ok()?;
130 Some((id.to_owned(), Entry { count, last }))
131 })
132 .collect();
133 Self { entries }
134 }
135}
136
137fn weight(entry: Entry, now: u64) -> f64 {
138 frecency(entry.count, entry.last, now)
139}
140
141#[must_use]
145#[allow(
146 clippy::cast_precision_loss,
147 reason = "counts and ages are far below 2^52"
148)]
149pub fn frecency(count: u32, last: u64, now: u64) -> f64 {
150 let age_days = now.saturating_sub(last) as f64 / SECONDS_PER_DAY;
151 (1.0 + f64::from(count)).ln() * 0.5_f64.powf(age_days / HALF_LIFE_DAYS)
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157
158 const DAY: u64 = 86_400;
159
160 #[test]
161 fn usage_boosts_what_is_chosen_often_and_lately_and_keeps_the_most_used() {
162 {
164 let mut usage = Frecency::default();
165 let now = 100 * DAY;
166 for _ in 0..12 {
167 usage.record("daily", now - DAY);
168 }
169 usage.record("once-recently", now - DAY);
170 usage.record("once-long-ago", now - 90 * DAY);
171 let daily = usage.boost("daily", now, 8);
172 let recent = usage.boost("once-recently", now, 8);
173 let old = usage.boost("once-long-ago", now, 8);
174 assert!(daily > recent && recent > old, "{daily} {recent} {old}");
175 assert_eq!(usage.boost("never", now, 8), 0);
176 assert!(daily <= 8);
177 }
178
179 {
181 let mut usage = Frecency::default();
182 for _ in 0..30 {
183 usage.record("app", 0);
184 }
185 assert_eq!(usage.boost("app", 0, 8), 8);
186 assert!(usage.boost("app", 60 * DAY, 8) < 8);
187 }
188
189 {
191 let mut usage = Frecency::default();
192 usage.record("so.tilo.tube", 5);
193 usage.record("so.tilo.tube", 9);
194 let mut text = usage.serialize();
195 text.push_str("broken line\n\tx\ty\n");
196 assert_eq!(Frecency::parse(&text), usage);
197 }
198
199 {
201 let mut usage = Frecency::default();
202 usage.record("a", 10);
203 usage.record("b", 30);
204 for _ in 0..6 {
205 usage.record("c", 20);
206 }
207 assert!(usage.share("c", 40) > usage.share("a", 40));
208 assert!(usage.share("a", 40) > 0.0 && usage.share("c", 40) <= 1.0);
209 assert!(usage.share("never", 40).abs() < f32::EPSILON);
210 assert_eq!(usage.most_recent(2), ["b", "c"]);
211 assert_eq!(usage.most_recent(9), ["b", "c", "a"]);
212 }
213
214 {
216 let mut usage = Frecency::default();
217 for _ in 0..5 {
218 usage.record("favourite", 10);
219 }
220 for at in 0..=MAX_ENTRIES {
221 usage.record(&format!("one-off-{at}"), 10);
222 }
223 assert!(usage.entries.len() <= MAX_ENTRIES);
224 assert!(usage.boost("favourite", 10, 8) > 0);
225 }
226 }
227}