fe_common/utils/
humanize.rs

1/// A trait to derive plural or singular representations from
2pub trait Pluralizable {
3    fn to_plural(&self) -> String;
4
5    fn to_singular(&self) -> String;
6}
7
8impl Pluralizable for &str {
9    fn to_plural(&self) -> String {
10        if self.ends_with('s') {
11            self.to_string()
12        } else {
13            format!("{self}s")
14        }
15    }
16
17    fn to_singular(&self) -> String {
18        if self.ends_with('s') {
19            self[0..self.len() - 1].to_string()
20        } else {
21            self.to_string()
22        }
23    }
24}
25
26// Impl Pluralizable for (singular, plural)
27impl Pluralizable for (&str, &str) {
28    fn to_plural(&self) -> String {
29        self.1.to_string()
30    }
31
32    fn to_singular(&self) -> String {
33        self.0.to_string()
34    }
35}
36
37// Pluralize the given pluralizable if the `count` is greater than one.
38pub fn pluralize_conditionally(pluralizable: impl Pluralizable, count: usize) -> String {
39    if count == 1 {
40        pluralizable.to_singular()
41    } else {
42        pluralizable.to_plural()
43    }
44}