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
use super::{Record, StackedRecord};
use crate::{Error, Stack, COLUMN_SEPARATOR};
use core::{
    fmt::{self, Display, Formatter},
    str::FromStr,
};

/// A duration record.
#[derive(Debug, Clone, Eq, PartialEq)]
pub struct DurationRecord {
    stack: Stack,
    time: u128,
}

impl DurationRecord {
    /// Creates a record.
    pub const fn new(stack: Stack, time: u128) -> Self {
        Self { stack, time }
    }

    /// Returns a time.
    pub const fn time(&self) -> u128 {
        self.time
    }
}

impl FromStr for DurationRecord {
    type Err = Error;

    fn from_str(string: &str) -> Result<Self, Self::Err> {
        let mut iterator = string.split(COLUMN_SEPARATOR);

        Ok(Self::new(
            iterator.next().ok_or(Error::MissingStack)?.parse()?,
            iterator.next().ok_or(Error::MissingTime)?.parse()?,
        ))
    }
}

impl Display for DurationRecord {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}", &self.stack)?;
        write!(formatter, "{COLUMN_SEPARATOR}")?;
        write!(formatter, "{}", &self.time)?;

        Ok(())
    }
}

impl Record for DurationRecord {}

impl StackedRecord for DurationRecord {
    fn stack(&self) -> &Stack {
        &self.stack
    }

    fn stack_mut(&mut self) -> &mut Stack {
        &mut self.stack
    }
}

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

    #[test]
    fn parse() {
        let record =
            DurationRecord::new(Stack::new(vec![Some("foo".into()), Some("bar".into())]), 42);

        assert_eq!(
            record.to_string().parse::<DurationRecord>().unwrap(),
            record
        );
    }
}