/ src / utils / fmt.rs
fmt.rs
 1  use std::fmt::{Display, from_fn};
 2  
 3  use chrono::TimeDelta;
 4  
 5  pub fn fmt_rank(rank: usize) -> impl Display {
 6      from_fn(move |f| {
 7          let medal = match rank {
 8              1 => "🥇 ",
 9              2 => "🥈 ",
10              3 => "🥉 ",
11              _ => "",
12          };
13          let suffix = match (rank / 10 % 10, rank % 10) {
14              (1, _) => "th",
15              (_, 1) => "st",
16              (_, 2) => "nd",
17              (_, 3) => "rd",
18              _ => "th",
19          };
20          write!(f, "{medal}{rank}{suffix}")
21      })
22  }
23  
24  pub fn fmt_timedelta(td: TimeDelta) -> impl Display {
25      from_fn(move |f| {
26          let s = td.num_seconds() % 60;
27          let m = td.num_minutes() % 60;
28          let h = td.num_hours() % 24;
29          let d = td.num_days();
30          if td.num_days() >= 1 {
31              write!(f, "{d}d {h}h {m}m {s}s")
32          } else if td.num_hours() >= 1 {
33              write!(f, "{h}h {m}m {s}s")
34          } else if td.num_minutes() >= 1 {
35              write!(f, "{m}m {s}s")
36          } else {
37              write!(f, "{s}s")
38          }
39      })
40  }
41  
42  pub fn fmt_option<T: Display>(opt: Option<&T>) -> impl Display {
43      from_fn(move |f| opt.map(|x| x.fmt(f)).unwrap_or(Ok(())))
44  }