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::Visitor;
20
21/// A diagnostic that stores key-value pairs in a static global map.
22///
23/// ## Example
24///
25/// ```
26/// use logforth_core::diagnostic::StaticDiagnostic;
27///
28/// let mut diagnostic = StaticDiagnostic::default();
29/// diagnostic.insert("key", "value");
30/// ```
31#[derive(Default, Debug, Clone)]
32#[non_exhaustive]
33pub struct StaticDiagnostic {
34 kvs: BTreeMap<String, String>,
35}
36
37impl StaticDiagnostic {
38 /// Creates a new [`StaticDiagnostic`] instance with a prebuilt key-value store.
39 pub fn new(kvs: BTreeMap<String, String>) -> Self {
40 Self { kvs }
41 }
42
43 /// Inserts a key-value pair into the static diagnostic .
44 pub fn insert<K, V>(&mut self, key: K, value: V)
45 where
46 K: Into<String>,
47 V: Into<String>,
48 {
49 self.kvs.insert(key.into(), value.into());
50 }
51
52 /// Remove a key-value pair from the static diagnostic.
53 pub fn remove(&mut self, key: &str) {
54 self.kvs.remove(key);
55 }
56}
57
58fn do_visit(d: &StaticDiagnostic, visitor: &mut dyn Visitor) -> Result<(), Error> {
59 for (key, value) in d.kvs.iter() {
60 visitor.visit(key.as_str().into(), value.as_str().into())?;
61 }
62 Ok(())
63}
64
65impl Diagnostic for StaticDiagnostic {
66 fn visit(&self, visitor: &mut dyn Visitor) -> Result<(), Error> {
67 do_visit(self, visitor)
68 }
69}
70
71impl Diagnostic for &'static StaticDiagnostic {
72 fn visit(&self, visitor: &mut dyn Visitor) -> Result<(), Error> {
73 do_visit(self, visitor)
74 }
75}