1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
use nom::{
bytes::complete::take_while1, character::complete::space1, combinator::map,
sequence::separated_pair, IResult,
};
pub use self::expression::{ConversionError, Expression, Value};
mod expression;
#[derive(Debug, Clone, PartialEq)]
pub struct Amount<'a> {
expression: Expression,
currency: &'a str,
}
impl<'a> Amount<'a> {
#[cfg(test)]
pub(crate) fn new(value: impl Into<rust_decimal::Decimal>, currency: &'a str) -> Self {
Self {
expression: Expression::value(value),
currency,
}
}
#[must_use]
pub fn expression(&self) -> &Expression {
&self.expression
}
#[must_use]
pub fn value(&self) -> Value {
self.expression.evaluate()
}
#[must_use]
pub fn currency(&self) -> &str {
self.currency
}
}
pub(crate) fn amount(input: &str) -> IResult<&str, Amount<'_>> {
map(
separated_pair(expression::parse, space1, currency),
|(expression, currency)| Amount {
expression,
currency,
},
)(input)
}
pub(crate) fn currency(input: &str) -> IResult<&str, &str> {
take_while1(|c: char| c.is_ascii_uppercase() && c.is_ascii_alphabetic())(input)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_amount() {
assert_eq!(
amount("10 CHF"),
Ok((
"",
Amount {
expression: Expression::value(10),
currency: "CHF"
}
))
);
}
#[test]
fn invalid_amount() {
assert!(amount("10 chf").is_err());
}
}