thousands/
traits.rs

1use super::{SeparatorPolicy, policies};
2
3/// Provides methods for formatting numbers with separators between the digits.
4pub trait Separable {
5    /// Inserts a comma every three digits from the right.
6    ///
7    /// This is equivalent to `self.separate_by_policy(policies::COMMA_SEPARATOR)`.
8    ///
9    /// # Examples
10    ///
11    /// ```
12    /// # use thousands::*;
13    /// assert_eq!( 12345.separate_with_commas(), "12,345" );
14    /// ```
15    fn separate_with_commas(&self) -> String {
16        self.separate_by_policy(policies::COMMA_SEPARATOR)
17    }
18
19    /// Inserts a space every three digits from the right.
20    ///
21    /// This is equivalent to `self.separate_by_policy(policies::SPACE_SEPARATOR)`.
22    ///
23    /// # Examples
24    ///
25    /// ```
26    /// # use thousands::*;
27    /// assert_eq!( 12345.separate_with_spaces(), "12 345" );
28    /// ```
29    fn separate_with_spaces(&self) -> String {
30        self.separate_by_policy(policies::SPACE_SEPARATOR)
31    }
32
33    /// Inserts a period every three digits from the right.
34    ///
35    /// This is equivalent to `self.separate_by_policy(policies::DOT_SEPARATOR)`.
36    ///
37    /// # Examples
38    ///
39    /// ```
40    /// # use thousands::*;
41    /// assert_eq!( 12345.separate_with_dots(), "12.345" );
42    /// ```
43    fn separate_with_dots(&self) -> String {
44        self.separate_by_policy(policies::DOT_SEPARATOR)
45    }
46
47    /// Inserts an underscore every three digits from the right.
48    ///
49    /// This is equivalent to `self.separate_by_policy(policies::UNDERSCORE_SEPARATOR)`.
50    ///
51    /// # Examples
52    ///
53    /// ```
54    /// # use thousands::*;
55    /// assert_eq!( 12345.separate_with_underscores(), "12_345" );
56    /// ```
57    fn separate_with_underscores(&self) -> String {
58        self.separate_by_policy(policies::UNDERSCORE_SEPARATOR)
59    }
60
61    /// Adds separators according to the given [`SeparatorPolicy`].
62    ///
63    /// # Examples
64    ///
65    /// ```
66    /// use thousands::{Separable, SeparatorPolicy, digits};
67    ///
68    /// let policy = SeparatorPolicy {
69    ///     separator:  ":",
70    ///     groups:     &[1, 2, 3, 4],
71    ///     digits:     digits::ASCII_DECIMAL,
72    /// };
73    ///
74    /// assert_eq!( 1234567654321u64.separate_by_policy(policy),
75    ///             "123:4567:654:32:1" );
76    /// ```
77    ///
78    /// [`SeparatorPolicy`]: struct.SeparatorPolicy.html
79    fn separate_by_policy(&self, policy: SeparatorPolicy) -> String;
80}
81