Skip to main content

endpoint_libs/libs/
warn.rs

1use alloc::string::{String, ToString};
2#[cfg(feature = "std")]
3use std::collections::HashMap;
4#[cfg(not(feature = "std"))]
5use alloc::collections::BTreeMap as HashMap;
6use tracing::warn;
7
8#[derive(Debug)]
9pub struct WarnStats {
10    pub warn_count: u64,
11}
12#[derive(Debug, Default)]
13pub struct WarnManager {
14    warns: HashMap<String, WarnStats>,
15}
16
17impl WarnManager {
18    pub fn new() -> Self {
19        Self {
20            warns: HashMap::new(),
21        }
22    }
23
24    pub fn warn(&mut self, s: impl AsRef<str>) {
25        let s = s.as_ref();
26
27        if let Some(stats) = self.warns.get_mut(s) {
28            stats.warn_count += 1;
29        } else {
30            warn!("First warning: {}", s);
31            self.warns
32                .insert(s.to_string(), WarnStats { warn_count: 1 });
33        }
34    }
35    pub fn get_warns(&self) -> &HashMap<String, WarnStats> {
36        &self.warns
37    }
38
39    #[cfg(feature = "std")]
40    pub fn dump_stats(&self, mut file: impl std::io::Write) -> std::io::Result<()> {
41        writeln!(file, "Warnings at {}:", chrono::Utc::now())?;
42        for (msg, stats) in &self.warns {
43            writeln!(file, "count={} warn={}", stats.warn_count, msg)?;
44        }
45        Ok(())
46    }
47
48    #[cfg(not(feature = "std"))]
49    pub fn dump_stats(&self, mut file: impl core::fmt::Write) -> core::fmt::Result {
50        writeln!(file, "Warnings at {}:", crate::libs::utils::get_time_milliseconds())?;
51        for (msg, stats) in &self.warns {
52            writeln!(file, "count={} warn={}", stats.warn_count, msg)?;
53        }
54        Ok(())
55    }
56}