Debian Codegraph @

src/output/pluralize.rs

raw
1 //! Lightweight pluralization support.
2
3 use std::fmt;
4
5 use crate::output::wrapping::NBSP;
6
7 /// Pluralizes countable things when formatted.
8 pub struct Pluralized<'t, 's> {
9 /// The amount of things we have.
10 count: usize,
11
12 /// Of these things.
13 thing: &'t str,
14
15 /// Use this plural suffix.
16 plural_suffix: &'s str,
17 }
18
19 impl fmt::Display for Pluralized<'_, '_> {
20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21 write!(f, "{}{}{}{}",
22 self.count,
23 NBSP,
24 self.thing,
25 if self.count == 1 { "" } else { self.plural_suffix })
26 }
27 }
28
29 impl<'t, 's> Pluralized<'t, 's> {
30 /// Changes the plural suffix.
31 pub fn plural<'n>(self, suffix: &'n str) -> Pluralized<'t, 'n> {
32 Pluralized {
33 count: self.count,
34 thing: self.thing,
35 plural_suffix: suffix,
36 }
37 }
38 }
39
40 /// Provides convenient pluralization.
41 ///
42 /// # Examples
43 ///
44 /// ```
45 /// use Pluralize;
46 /// assert_eq!(&3.of("apple").to_string(), "3 apples");
47 /// assert_eq!(&2.of("bus").plural("es").to_string(), "2 buses");
48 /// ```
49 pub trait Pluralize<'t> {
50 fn of(self, thing: &'t str) -> Pluralized<'t, 'static>;
51 }
52
53 impl<'t> Pluralize<'t> for usize {
54 fn of(self, thing: &'t str) -> Pluralized<'t, 'static> {
55 Pluralized {
56 count: self,
57 thing: thing,
58 plural_suffix: "s",
59 }
60 }
61 }