ph_temp/stats.rs
1//! Collecting and reporting building and querying statistics.
2
3use std::io::Write;
4
5/// Trait for collecting (and summarizing or reporting) events during construction of a minimal perfect hashing function.
6pub trait BuildStatsCollector {
7 /// Called once at each level to indicate sizes of input and level. Default implementation do nothing.
8 #[inline(always)] fn level(&mut self, _input_size: usize, _level_size: usize) {}
9
10 /// Called once at the end of the building process with number of remaining (unsupported) keys (0 when construction has been successful).
11 /// Default implementation do nothing.
12 #[inline(always)] fn end(&mut self, _remaining_keys: usize) {}
13}
14
15/// Ignores all events and does nothing.
16impl BuildStatsCollector for () {}
17
18/// Report events occurred during building a minimal perfect hashing function to the wrapped writer.
19pub struct BuildStatsPrinter<W: Write = std::io::Stdout>(W);
20
21impl BuildStatsPrinter<std::io::Stdout> {
22 /// Report events occurred during building a minimal perfect hashing function to the standard output.
23 pub fn stdout() -> Self { Self(std::io::stdout()) }
24}
25
26impl<W: Write> BuildStatsCollector for BuildStatsPrinter<W> {
27 fn level(&mut self, input_size: usize, level_size: usize) {
28 writeln!(self.0, "{} {}", input_size, level_size).unwrap();
29 }
30
31 fn end(&mut self, remaining_keys: usize) {
32 writeln!(self.0, "Completed {}. {} keys remaining.", if remaining_keys == 0 { "successfully" } else { "unsuccessfully" }, remaining_keys).unwrap();
33 }
34}
35
36/// Trait for collecting (and summarizing or reporting) events during querying of a minimal perfect hashing function.
37pub trait AccessStatsCollector {
38 /// Lookup algorithm calls this method to report that a value has been just found at given level (counting from 0).
39 /// The single lookup can call `found_on_level` few times if it finds the fragments on value at different levels.
40 #[inline(always)] fn found_on_level(&mut self, _level_nr: usize) {}
41
42 /// Lookup algorithm calls this method to report that a value has not been found and reports number of level searched (counting from 0).
43 #[inline(always)] fn fail_on_level(&mut self, _level_nr: usize) {}
44}
45
46/// Ignores all events and does nothing.
47impl AccessStatsCollector for () {}
48
49/// Increases own value by the number of levels visited, regardless of the result of the search.
50impl AccessStatsCollector for usize {
51 #[inline(always)] fn found_on_level(&mut self, level_nr: usize) { *self += level_nr + 1; }
52 #[inline(always)] fn fail_on_level(&mut self, level_nr: usize) { *self += level_nr + 1; }
53}