af_core/fmt/
count.rs

1// Copyright © 2021 Alexandra Frydl
2//
3// This Source Code Form is subject to the terms of the Mozilla Public
4// License, v. 2.0. If a copy of the MPL was not distributed with this
5// file, You can obtain one at http://mozilla.org/MPL/2.0/.
6
7use super::*;
8use crate::math::One;
9use crate::prelude::*;
10
11/// Displays a correctly pluralized count of something, for example `3 users`.
12pub struct Counted<'a, T> {
13  pub count: T,
14  pub one: &'a str,
15  pub many: &'a str,
16}
17
18/// Displays a correctly pluralized count of something, for example `3 users`.
19pub fn count<'a, T>(count: T, one: &'a str, many: &'a str) -> Counted<'a, T> {
20  Counted { count, one, many }
21}
22
23impl<'a, T> Display for Counted<'a, T>
24where
25  T: Display + One + PartialEq,
26{
27  fn fmt(&self, f: &mut Formatter) -> fmt::Result {
28    Display::fmt(&self.count, f)?;
29
30    match self.count.is_one() {
31      true => write!(f, " {}", self.one),
32      false => write!(f, " {}", self.many),
33    }
34  }
35}