notatin/
log.rs

1/*
2 * Copyright 2023 Aon Cyber Solutions
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use crate::err::Error;
18use serde::Serialize;
19use std::fmt;
20use std::io::{BufWriter, Write};
21
22#[derive(Clone, Debug, Default, Eq, PartialEq, Serialize)]
23pub struct Logs {
24    logs: Option<Vec<Log>>,
25}
26
27impl Logs {
28    pub(crate) fn add<T: ToString>(&mut self, code: LogCode, text: &T) {
29        self.add_internal(Log {
30            code,
31            text: text.to_string(),
32        });
33    }
34
35    fn add_internal(&mut self, warning: Log) {
36        match &mut self.logs {
37            Some(logs) => logs.push(warning),
38            None => self.logs = Some(vec![warning]),
39        }
40    }
41
42    pub fn has_logs(&self) -> bool {
43        self.logs.is_some()
44            && !self
45                .logs
46                .as_ref()
47                .expect("just checked is_some()")
48                .is_empty()
49    }
50
51    pub fn get(&self) -> Option<&Vec<Log>> {
52        self.logs.as_ref()
53    }
54
55    pub(crate) fn get_option(self) -> Option<Self> {
56        if self.logs.is_none() {
57            None
58        } else {
59            Some(self)
60        }
61    }
62
63    pub(crate) fn prepend_all(&mut self, prefix: &str) {
64        if let Some(logs) = &mut self.logs {
65            for log in logs {
66                log.text = format!("{}{}", prefix, log.text)
67            }
68        }
69    }
70
71    pub(crate) fn extend(&mut self, additional: Self) {
72        match &mut self.logs {
73            Some(logs) => logs.extend(additional.logs.unwrap_or_default()),
74            None => self.logs = Some(additional.logs.unwrap_or_default()),
75        }
76    }
77
78    pub fn write<W: Write>(&self, writer: &mut BufWriter<std::fs::File>) -> Result<(), Error> {
79        if let Some(logs) = &self.logs {
80            for log in logs {
81                writeln!(writer, "{:?} {}", log.code, log.text)?;
82            }
83        }
84        Ok(())
85    }
86
87    pub(crate) fn get_string(&self) -> String {
88        let mut ret = String::new();
89        if let Some(logs) = &self.logs {
90            for log in logs {
91                ret += &format!("{:?} {};", log.code, log.text);
92            }
93        }
94        ret
95    }
96}
97
98impl fmt::Display for Logs {
99    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
100        write!(f, "{}", self.get_string())
101    }
102}
103
104#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
105pub enum LogCode {
106    WarningOther,
107    WarningNom,
108    WarningConversion,
109    WarningContent,
110    WarningBigDataContent,
111    WarningUnrecognizedBitflag,
112    WarningTransactionLog,
113    WarningIterator,
114    WarningBaseBlock,
115    WarningParse,
116    WarningRecovery,
117    Info,
118}
119
120#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
121pub struct Log {
122    pub code: LogCode,
123    pub text: String,
124}