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
use crate::amount::{amount, currency};
use crate::date::date;
use crate::string::comment;
use crate::{Amount, Date};
use nom::bytes::complete::tag;
use nom::character::complete::space0;
use nom::character::streaming::space1;
use nom::combinator::{map, opt};
use nom::sequence::{preceded, terminated, tuple};
use nom::IResult;

/// A price directive
///
/// # Example
/// ```beancount
/// 2014-07-09 price HOOL  579.18 USD
/// ```
#[derive(Debug, Clone)]
pub struct Price<'a> {
    date: Date,
    commodity: &'a str,
    price: Amount<'a>,
    comment: Option<&'a str>,
}

impl<'a> Price<'a> {
    /// The date
    #[must_use]
    pub fn date(&self) -> Date {
        self.date
    }

    /// The commodity for which thi price applies
    #[must_use]
    pub fn commodity(&self) -> &'a str {
        self.commodity
    }

    /// The price of the commodity
    #[must_use]
    pub fn price(&self) -> &Amount<'a> {
        &self.price
    }

    /// The comment, if any
    #[must_use]
    pub fn comment(&self) -> Option<&'a str> {
        self.comment
    }
}

pub(crate) fn price(input: &str) -> IResult<&str, Price<'_>> {
    map(
        tuple((
            terminated(date, tuple((space1, tag("price"), space1))),
            terminated(currency, space1),
            amount,
            opt(preceded(space0, comment)),
        )),
        |(date, commodity, price, comment)| Price {
            date,
            commodity,
            price,
            comment,
        },
    )(input)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn simple() {
        let input = "2014-07-09 price HOOL  600 USD";
        let (_, price) = price(input).expect("should successfully parse the input");
        assert_eq!(price.date(), Date::new(2014, 7, 9));
        assert_eq!(price.commodity(), "HOOL");
        assert_eq!(price.price(), &Amount::new(600, "USD"));
        assert_eq!(price.comment(), None);
    }

    #[test]
    fn comment() {
        let input = "2014-07-09 price HOOL  600 USD ; with comment";
        let (_, price) = price(input).expect("should successfully parse the input");
        assert_eq!(price.comment(), Some("with comment"));
    }
}