logforth_core/diagnostic/
static_global.rs

1// Copyright 2024 FastLabs Developers
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use std::collections::BTreeMap;
16
17use crate::Diagnostic;
18use crate::Error;
19use crate::kv::Key;
20use crate::kv::Value;
21use crate::kv::Visitor;
22
23/// A diagnostic that stores key-value pairs in a static global map.
24///
25/// ## Example
26///
27/// ```
28/// use logforth_core::diagnostic::StaticDiagnostic;
29///
30/// let mut diagnostic = StaticDiagnostic::default();
31/// diagnostic.insert("key", "value");
32/// ```
33#[derive(Default, Debug, Clone)]
34#[non_exhaustive]
35pub struct StaticDiagnostic {
36    kvs: BTreeMap<String, String>,
37}
38
39impl StaticDiagnostic {
40    /// Create a new [`StaticDiagnostic`] instance with a prebuilt key-value store.
41    pub fn new(kvs: BTreeMap<String, String>) -> Self {
42        Self { kvs }
43    }
44
45    /// Insert a key-value pair into the static diagnostic .
46    pub fn insert<K, V>(&mut self, key: K, value: V)
47    where
48        K: Into<String>,
49        V: Into<String>,
50    {
51        self.kvs.insert(key.into(), value.into());
52    }
53
54    /// Remove a key-value pair from the static diagnostic.
55    pub fn remove(&mut self, key: &str) {
56        self.kvs.remove(key);
57    }
58}
59
60fn do_visit(d: &StaticDiagnostic, visitor: &mut dyn Visitor) -> Result<(), Error> {
61    for (key, value) in d.kvs.iter() {
62        let key = Key::new_ref(key.as_str());
63        let value = Value::from(value);
64        visitor.visit(key, value)?;
65    }
66    Ok(())
67}
68
69impl Diagnostic for StaticDiagnostic {
70    fn visit(&self, visitor: &mut dyn Visitor) -> Result<(), Error> {
71        do_visit(self, visitor)
72    }
73}
74
75impl Diagnostic for &'static StaticDiagnostic {
76    fn visit(&self, visitor: &mut dyn Visitor) -> Result<(), Error> {
77        do_visit(self, visitor)
78    }
79}