stak_profiler/record/
procedure_record.rs

1use super::{Record, StackedRecord};
2use crate::{COLUMN_SEPARATOR, Error, ProcedureOperation, Stack};
3use core::{
4    fmt::{self, Display, Formatter},
5    str::FromStr,
6};
7
8/// A procedure record.
9#[derive(Debug, Clone, Eq, PartialEq)]
10pub struct ProcedureRecord {
11    operation: ProcedureOperation,
12    stack: Stack,
13    time: u128,
14}
15
16impl ProcedureRecord {
17    /// Creates a new record.
18    pub const fn new(operation: ProcedureOperation, stack: Stack, time: u128) -> Self {
19        Self {
20            operation,
21            stack,
22            time,
23        }
24    }
25
26    /// Returns a procedure operation.
27    pub const fn operation(&self) -> ProcedureOperation {
28        self.operation
29    }
30
31    /// Returns a time.
32    pub const fn time(&self) -> u128 {
33        self.time
34    }
35}
36
37impl FromStr for ProcedureRecord {
38    type Err = Error;
39
40    fn from_str(string: &str) -> Result<Self, Self::Err> {
41        let mut iterator = string.split(COLUMN_SEPARATOR);
42
43        Ok(Self::new(
44            iterator
45                .next()
46                .ok_or(Error::MissingProcedureOperation)?
47                .parse()?,
48            iterator.next().ok_or(Error::MissingStack)?.parse()?,
49            iterator.next().ok_or(Error::MissingTime)?.parse()?,
50        ))
51    }
52}
53
54impl Display for ProcedureRecord {
55    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
56        write!(formatter, "{}", self.operation)?;
57        write!(formatter, "{COLUMN_SEPARATOR}")?;
58        write!(formatter, "{}", &self.stack)?;
59        write!(formatter, "{COLUMN_SEPARATOR}")?;
60        write!(formatter, "{}", &self.time)?;
61
62        Ok(())
63    }
64}
65
66impl Record for ProcedureRecord {}
67
68impl StackedRecord for ProcedureRecord {
69    fn stack(&self) -> &Stack {
70        &self.stack
71    }
72
73    fn stack_mut(&mut self) -> &mut Stack {
74        &mut self.stack
75    }
76}
77
78#[cfg(test)]
79mod tests {
80    use super::*;
81    use pretty_assertions::assert_eq;
82
83    #[test]
84    fn parse() {
85        let record = ProcedureRecord::new(
86            ProcedureOperation::Call,
87            Stack::new(vec![Some("foo".into()), Some("bar".into())]),
88            42,
89        );
90
91        assert_eq!(
92            record.to_string().parse::<ProcedureRecord>().unwrap(),
93            record
94        );
95    }
96}