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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
use std::collections::{HashMap, HashSet};
use std::io;

use crate::core::types::StackFrame;

struct Counts {
    self_: u64,
    total: u64,
}

pub struct Stats {
    counts: HashMap<String, Counts>,
    start_time: std::time::Instant,
    total_traces: u32,
}

impl Stats {
    const HEADER: &'static str = "% self  % total  name";

    pub fn new() -> Stats {
        Stats {
            counts: HashMap::new(),
            start_time: std::time::Instant::now(),
            total_traces: 0,
        }
    }

    fn inc_self(&mut self, name: String) {
        let entry = self
            .counts
            .entry(name)
            .or_insert(Counts { self_: 0, total: 0 });
        entry.self_ += 1;
    }

    fn inc_tot(&mut self, name: String) {
        let entry = self
            .counts
            .entry(name)
            .or_insert(Counts { self_: 0, total: 0 });
        entry.total += 1;
    }

    fn name_function(frame: &StackFrame) -> String {
        format!("{} - {}", frame.name, frame.relative_path)
    }

    fn name_lineno(frame: &StackFrame) -> String {
        format!("{}", frame)
    }

    // Aggregate by function name
    pub fn add_function_name(&mut self, stack: &[StackFrame]) {
        if stack.is_empty() {
            return;
        }
        self.total_traces += 1;
        self.inc_self(Stats::name_function(&stack[0]));
        let mut set: HashSet<String> = HashSet::new();
        for frame in stack {
            set.insert(Stats::name_function(frame));
        }
        for name in set.into_iter() {
            self.inc_tot(name);
        }
    }

    // Aggregate by function name + line number
    pub fn add_lineno(&mut self, stack: &[StackFrame]) {
        if stack.is_empty() {
            return;
        }
        self.total_traces += 1;
        self.inc_self(Stats::name_lineno(&stack[0]));
        let mut set: HashSet<&StackFrame> = HashSet::new();
        for frame in stack {
            set.insert(&frame);
        }
        for frame in set {
            self.inc_tot(Stats::name_lineno(frame));
        }
    }

    pub fn write(&self, w: &mut dyn io::Write) -> io::Result<()> {
        self.write_counts(w, None, None)
    }

    pub fn write_top_n(
        &self,
        w: &mut dyn io::Write,
        n: usize,
        truncate: Option<usize>,
    ) -> io::Result<()> {
        self.write_counts(w, Some(n), truncate)
    }

    pub fn elapsed_time(&self) -> std::time::Duration {
        std::time::Instant::now() - self.start_time
    }

    fn write_counts(
        &self,
        w: &mut dyn io::Write,
        top: Option<usize>,
        truncate: Option<usize>,
    ) -> io::Result<()> {
        let top = top.unwrap_or(::std::usize::MAX);
        let truncate = truncate.unwrap_or(::std::usize::MAX);
        let mut sorted: Vec<(u64, u64, &str)> = self
            .counts
            .iter()
            .map(|(x, y)| (y.self_, y.total, x.as_ref()))
            .collect();
        sorted.sort_unstable();
        let counts = sorted.iter().rev().take(top);
        writeln!(w, "{}", Stats::HEADER)?;
        for &(self_, total, name) in counts {
            writeln!(
                w,
                "{:>6.2} {:>8.2}  {:.*}",
                100.0 * (self_ as f64) / f64::from(self.total_traces),
                100.0 * (total as f64) / f64::from(self.total_traces),
                truncate - 14 - 3,
                name
            )?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use crate::ui::summary::*;

    // Build a test stackframe
    fn f(i: u32) -> StackFrame {
        StackFrame {
            name: format!("func{}", i),
            relative_path: format!("file{}.rb", i),
            absolute_path: None,
            lineno: i,
        }
    }

    #[test]
    fn stats_by_function() {
        let mut stats = Stats::new();

        stats.add_function_name(&vec![f(1)]);
        stats.add_function_name(&vec![f(3), f(2), f(1)]);
        stats.add_function_name(&vec![f(2), f(1)]);
        stats.add_function_name(&vec![f(3), f(1)]);
        stats.add_function_name(&vec![f(2), f(3), f(1)]);

        let expected = "% self  % total  name
 40.00    60.00  func3 - file3.rb
 40.00    60.00  func2 - file2.rb
 20.00   100.00  func1 - file1.rb
";

        let mut buf: Vec<u8> = Vec::new();
        stats.write(&mut buf).expect("Callgrind write failed");
        let actual = String::from_utf8(buf).expect("summary output not utf8");
        assert_eq!(actual, expected, "Unexpected summary output");
    }

    #[test]
    fn stats_by_line_number() {
        let mut stats = Stats::new();

        stats.add_lineno(&vec![f(1)]);
        stats.add_lineno(&vec![f(3), f(2), f(1)]);
        stats.add_lineno(&vec![f(2), f(1)]);
        stats.add_lineno(&vec![f(3), f(1)]);
        stats.add_lineno(&vec![f(2), f(3), f(1)]);

        let expected = "% self  % total  name
 40.00    60.00  func3 - file3.rb:3
 40.00    60.00  func2 - file2.rb:2
 20.00   100.00  func1 - file1.rb:1
";

        let mut buf: Vec<u8> = Vec::new();
        stats.write(&mut buf).expect("summary write failed");
        let actual = String::from_utf8(buf).expect("summary output not utf8");
        assert_eq!(actual, expected, "Unexpected summary output");
    }
}