Skip to main content

inflect_rs/
types.rs

1use std::fmt;
2use std::str::FromStr;
3
4use crate::Error;
5
6/// A count used to decide between singular and plural forms.
7///
8/// Numbers and words are both accepted, mirroring the Python library: `1`,
9/// `"one"`, `"a"`, `"each"` and so on count as singular, anything else as
10/// plural.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub enum Count {
13    Num(i64),
14    Word(String),
15}
16
17impl fmt::Display for Count {
18    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19        match self {
20            Count::Num(n) => write!(f, "{n}"),
21            Count::Word(w) => f.write_str(w),
22        }
23    }
24}
25
26macro_rules! count_from_int {
27    ($($t:ty),*) => {
28        $(impl From<$t> for Count {
29            fn from(n: $t) -> Self {
30                match i64::try_from(n) {
31                    Ok(n) => Count::Num(n),
32                    Err(_) => Count::Word(n.to_string()),
33                }
34            }
35        })*
36    };
37}
38
39count_from_int!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
40
41impl From<&str> for Count {
42    fn from(s: &str) -> Self {
43        Count::Word(s.to_string())
44    }
45}
46
47impl From<String> for Count {
48    fn from(s: String) -> Self {
49        Count::Word(s)
50    }
51}
52
53impl From<&Count> for Count {
54    fn from(c: &Count) -> Self {
55        c.clone()
56    }
57}
58
59/// The gender used when singularizing third-person plural pronouns.
60#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
61pub enum Gender {
62    #[default]
63    Neuter,
64    Feminine,
65    Masculine,
66    GenderNeutral,
67    FeminineOrMasculine,
68    MasculineOrFeminine,
69}
70
71impl Gender {
72    pub const ALL: [Gender; 6] = [
73        Gender::Neuter,
74        Gender::Feminine,
75        Gender::Masculine,
76        Gender::GenderNeutral,
77        Gender::FeminineOrMasculine,
78        Gender::MasculineOrFeminine,
79    ];
80
81    pub fn as_str(self) -> &'static str {
82        match self {
83            Gender::Neuter => "neuter",
84            Gender::Feminine => "feminine",
85            Gender::Masculine => "masculine",
86            Gender::GenderNeutral => "gender-neutral",
87            Gender::FeminineOrMasculine => "feminine or masculine",
88            Gender::MasculineOrFeminine => "masculine or feminine",
89        }
90    }
91}
92
93impl fmt::Display for Gender {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        f.write_str(self.as_str())
96    }
97}
98
99impl FromStr for Gender {
100    type Err = Error;
101
102    fn from_str(s: &str) -> Result<Self, Self::Err> {
103        Gender::ALL
104            .into_iter()
105            .find(|g| g.as_str() == s)
106            .ok_or_else(|| Error::BadGender(s.to_string()))
107    }
108}
109
110/// Which classical (Latin/Greek or archaic) inflections to prefer.
111///
112/// The default enables only `names`, matching the Python library.
113#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
114pub struct Classical {
115    /// Prefer classical plurals everywhere a choice exists ("formulae", "indices").
116    pub all: bool,
117    /// Treat zero as singular when given as a word count ("no cat" rather than "no cats").
118    pub zero: bool,
119    /// Leave herd animals uninflected ("buffalo" rather than "buffalos").
120    pub herd: bool,
121    /// Pluralize proper names ending in -y with -s ("Marys" rather than "Maries").
122    pub names: bool,
123    /// Use "persons" rather than "people".
124    pub persons: bool,
125    /// Use classical plurals for incompletely assimilated imports ("cherubim").
126    pub ancient: bool,
127}
128
129impl Classical {
130    pub const fn all() -> Self {
131        Classical {
132            all: true,
133            zero: true,
134            herd: true,
135            names: true,
136            persons: true,
137            ancient: true,
138        }
139    }
140
141    pub const fn none() -> Self {
142        Classical {
143            all: false,
144            zero: false,
145            herd: false,
146            names: false,
147            persons: false,
148            ancient: false,
149        }
150    }
151}
152
153impl Default for Classical {
154    fn default() -> Self {
155        Classical {
156            names: true,
157            ..Classical::none()
158        }
159    }
160}
161
162/// The result of comparing two words regardless of plurality.
163#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
164pub enum Comparison {
165    /// The words are identical.
166    Eq,
167    /// The first word is the plural of the second.
168    PluralSingular,
169    /// The second word is the plural of the first.
170    SingularPlural,
171    /// The words are two different plural forms of the same word.
172    PluralPlural,
173}
174
175impl Comparison {
176    pub fn as_str(self) -> &'static str {
177        match self {
178            Comparison::Eq => "eq",
179            Comparison::PluralSingular => "p:s",
180            Comparison::SingularPlural => "s:p",
181            Comparison::PluralPlural => "p:p",
182        }
183    }
184}
185
186impl fmt::Display for Comparison {
187    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
188        f.write_str(self.as_str())
189    }
190}
191
192/// Options for [`Engine::number_to_words_with`](crate::Engine::number_to_words_with).
193#[derive(Clone, Debug, PartialEq)]
194pub struct NumberToWordsOptions {
195    /// Read digits in groups of 1, 2 or 3 ("one two three"); 0 reads the whole number.
196    pub group: u8,
197    pub comma: String,
198    /// The word between hundreds and tens ("one hundred and one"); may be empty.
199    pub andword: String,
200    pub zero: String,
201    pub one: String,
202    /// The word for a decimal point; `None` disables decimal handling.
203    pub decimal: Option<String>,
204    /// Numbers above this are returned as digits (with thousands commas) instead of words.
205    pub threshold: Option<i64>,
206}
207
208impl Default for NumberToWordsOptions {
209    fn default() -> Self {
210        NumberToWordsOptions {
211            group: 0,
212            comma: ",".to_string(),
213            andword: "and".to_string(),
214            zero: "zero".to_string(),
215            one: "one".to_string(),
216            decimal: Some("point".to_string()),
217            threshold: None,
218        }
219    }
220}
221
222/// Options for [`Engine::join_with`](crate::Engine::join_with).
223#[derive(Clone, Debug, PartialEq, Eq)]
224pub struct JoinOptions {
225    /// Separator between items; defaults to "," or ";" if any item contains a comma.
226    pub sep: Option<String>,
227    pub sep_spaced: bool,
228    /// Separator before the conjunction; defaults to `sep`.
229    pub final_sep: Option<String>,
230    pub conj: String,
231    pub conj_spaced: bool,
232}
233
234impl Default for JoinOptions {
235    fn default() -> Self {
236        JoinOptions {
237            sep: None,
238            sep_spaced: true,
239            final_sep: None,
240            conj: "and".to_string(),
241            conj_spaced: true,
242        }
243    }
244}