src/handlers/string_handler.rs

Lines

100.00 %

Functions

100.00 %

Regions

100.00 %

LineCountSource (jump to first uncovered line)
1
//
2
// File Name:    string_handler.rs
3
// Project Name: flogging
4
//
5
// Copyright (C) 2025 Bradley Willcott
6
//
7
// SPDX-License-Identifier: GPL-3.0-or-later
8
//
9
// This library (crate) is free software: you can redistribute it and/or modify
10
// it under the terms of the GNU General Public License as published by
11
// the Free Software Foundation, either version 3 of the License, or
12
// (at your option) any later version.
13
//
14
// This library (crate) is distributed in the hope that it will be useful,
15
// but WITHOUT ANY WARRANTY; without even the implied warranty of
16
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
// GNU General Public License for more details.
18
//
19
// You should have received a copy of the GNU General Public License
20
// along with this library (crate).  If not, see <https://www.gnu.org/licenses/>.
21
//
22
23
//!
24
//! # StringHandler
25
//!
26
use crate::*;
27
use std::{fmt, io::Error};
28
29
///
30
/// Publishes log entries to an internal list.
31
///
32
/// The list can then be accessed via: [get_log()][StringHandler::get_log()].
33
///
34
#[derive(Debug, Default)]
35
pub struct StringHandler {
36
    formatter: Formatter,
37
    log: Vec<String>,
38
}
39
40
impl StringHandler {
4112
    fn new() -> Self {
4212
        StringHandler {
4312
            formatter: FormatType::Simple.create(None),
4412
            log: Vec::new(),
4512
        }
4612
    }
47
484
    fn log(&self) -> String {
494
        let mut buf = String::new();
50
5110
        for s in &self.log {
5210
            buf.push_str(s);
5310
            buf.push('\n');
5410
        }
55
564
        buf
574
    }
58
}
59
60
impl fmt::Display for StringHandler {
611
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
621
        let len = self.formatter.to_string().len();
631
        let line = "-".repeat(len + 3);
64
651
        write!(f, "{}\n{line}\n{}", self.formatter, self.log())
661
    }
67
}
68
69
impl HandlerTrait for StringHandler {
7012
    fn create(_name: &str) -> Result<Self, Error>
7112
    where
7212
        Self: Sized,
73
    {
7412
        Ok(StringHandler::new())
7512
    }
76
771
    fn close(&mut self) {}
78
791
    fn flush(&mut self) {
801
        self.log.clear();
811
    }
82
831
    fn get_formatter(&self) -> Formatter {
841
        self.formatter.clone()
851
    }
86
873
    fn get_log(&self) -> String {
883
        self.log()
893
    }
90
911
    fn is_open(&self) -> bool {
921
        true
931
    }
94
95
    #[allow(private_interfaces)]
9630
    fn publish(&mut self, log_entry: &LogEntry) {
9730
        self.log.push(self.formatter.format(log_entry));
9830
    }
99
1001
    fn set_formatter(&mut self, formatter: Formatter) {
1011
        self.formatter = formatter;
1021
    }
103
104
    ///
105
    /// This is a 'NoOp' fn. Use `get_log()`, as this already
106
    /// has the required functionality.
107
    ///
1081
    fn set_test_mode(&mut self, _state: bool) {}
109
}
110
111
#[cfg(test)]
112
mod tests {
113
    use crate::*;
114
115
    #[test]
1161
    fn string_handler() {
1171
        let expected = "flogging::handlers::string_handler::tests-> [INFO   ] trait methods
1181
flogging::handlers::string_handler::tests-> [WARNING] The sky is falling!\n"
1191
            .to_string();
120
1211
        let mut log = Logger::string_logger(module_path!());
122
1231
        log.info("trait methods");
1241
        log.warning("The sky is falling!");
125
1261
        let handler = log.get_handler(crate::Handler::String).unwrap();
1271
        handler.set_test_mode(true);
1281
        assert!(handler.is_open());
1291
        assert_eq!(
1301
            handler.get_formatter().to_string(),
1311
            "dt_fmt: \"\" - fmt_string: \"{mod_path}->{fn_name} [{level:7}] {message}\""
1321
                .to_string()
133
        );
1341
        assert_eq!(expected, handler.get_log());
1351
        handler.flush();
136
1371
        assert_eq!(handler.get_log(), "".to_string());
1381
        handler.close();
1391
    }
140
}