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
86
87
88
89
90
91
92
use crate::close::close;
use crate::open::open;
use crate::price::{price, Price};
use crate::{Close, Open};
use nom::branch::alt;
use nom::{combinator::map, IResult};
use crate::transaction::{transaction, Transaction};
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Directive<'a> {
Transaction(Transaction<'a>),
Price(Price<'a>),
Open(Open<'a>),
Close(Close<'a>),
}
impl<'a> Directive<'a> {
#[must_use]
pub fn as_transaction(&self) -> Option<&Transaction<'a>> {
match self {
Directive::Transaction(trx) => Some(trx),
_ => None,
}
}
#[must_use]
pub fn into_transaction(self) -> Option<Transaction<'a>> {
match self {
Directive::Transaction(trx) => Some(trx),
_ => None,
}
}
}
pub(crate) fn directive(input: &str) -> IResult<&str, Directive<'_>> {
alt((
map(transaction, Directive::Transaction),
map(price, Directive::Price),
map(open, Directive::Open),
map(close, Directive::Close),
))(input)
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
#[test]
fn transaction() {
let input = r#"2022-09-10 txn "My transaction""#;
let (_, directive) = directive(input).expect("should successfully parse directive");
let transaction = directive
.as_transaction()
.expect("the directive should be a transaction");
assert_eq!(transaction.narration(), Some("My transaction"));
}
#[rstest]
fn invalid(
#[values(
"2022-09-11 txn that is incorrect",
"2022-09-11 * that is incorrect",
"2022-09-11 ! that is incorrect"
)]
input: &str,
) {
assert!(matches!(directive(input), Err(nom::Err::Failure(_))));
}
#[rstest]
fn not_matching(#[values(" ")] input: &str) {
assert!(matches!(directive(input), Err(nom::Err::Error(_))));
}
}