1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
//! (Advanced) Keeshond's default logger implementation

use rustc_hash::FxHasher;
use log::{Log, Record, Level, LevelFilter, Metadata, SetLoggerError};

use std::collections::HashSet;
use std::hash::BuildHasherDefault;
use std::sync::{Mutex, Arc};
use std::fmt::{Display, Formatter};

const DEFAULT_MAX_ENTRIES : usize = 4096;
const DEFAULT_MAX_MESSAGE_LENGTH : usize = 4096;
const MAX_SOURCE_LENGTH : usize = 256;

#[derive(Clone)]
pub struct ConsoleHistoryEntry
{
    pub level : Level,
    pub source : String,
    pub message : String
}

impl Default for ConsoleHistoryEntry
{
    fn default() -> Self
    {
        ConsoleHistoryEntry
        {
            level : Level::Trace,
            source : String::new(),
            message : String::new()
        }
    }
}

impl Display for ConsoleHistoryEntry
{
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result
    {
        write!(f, "[ {:5} {} ] {}", self.level, self.source, self.message)
    }
}

pub struct ConsoleHistory
{
    entries_ring : Vec<ConsoleHistoryEntry>,
    next_index : usize,
    max_entries : usize,
    max_message_len : usize
}

impl ConsoleHistory
{
    pub(crate) fn new() -> ConsoleHistory
    {
        ConsoleHistory::with_custom_limits(DEFAULT_MAX_ENTRIES, DEFAULT_MAX_MESSAGE_LENGTH)
    }

    pub(crate) fn with_custom_limits(max_entries : usize, max_message_len : usize) -> ConsoleHistory
    {
        let entries_ring = vec![ConsoleHistoryEntry::default(); max_entries];

        ConsoleHistory
        {
            entries_ring,
            next_index : 0,
            max_entries,
            max_message_len
        }
    }

    pub(crate) fn add_message(&mut self, entry : ConsoleHistoryEntry)
    {
        self.entries_ring[self.next_index % self.max_entries] = entry;

        self.next_index += 1;
    }

    pub fn history_min(&self) -> usize
    {
        if self.next_index > self.max_entries
        {
            return self.next_index - self.max_entries;
        }

        0
    }

    pub fn history_max(&self) -> usize
    {
        self.next_index
    }

    pub fn entry(&self, index : usize) -> Option<&ConsoleHistoryEntry>
    {
        if index >= self.history_min() && index < self.history_max()
        {
            return self.entries_ring.get(index % self.max_entries);
        }

        None
    }
}

pub struct DogLog
{
    allowed_packages : HashSet<String, BuildHasherDefault<FxHasher>>,
    history : Arc<Mutex<ConsoleHistory>>
}

fn prefix(text : &str, pos : usize) -> &str
{
    &text[..pos.min(text.len())]
}

impl DogLog
{
    pub fn new(history : Arc<Mutex<ConsoleHistory>>) -> DogLog
    {
        let mut allowed_packages = HashSet::with_hasher(BuildHasherDefault::<FxHasher>::default());
        allowed_packages.insert(String::from("keeshond"));
        allowed_packages.insert(String::from("keeshond_datapack"));
        allowed_packages.insert(String::from("keeshond_treats"));
        
        DogLog
        {
            allowed_packages,
            history
        }
    }
    
    pub fn add_package_filter(&mut self, package_name : String)
    {
        self.allowed_packages.insert(package_name);
    }
    
    pub fn install(self, max_level : LevelFilter) -> Result<(), SetLoggerError>
    {
        let result = log::set_boxed_logger(Box::new(self));
        
        if result.is_ok()
        {
            log::set_max_level(max_level);
        }
        
        result
    }
}

impl Log for DogLog
{
    fn enabled(&self, metadata: &Metadata) -> bool
    {
        let mut target : &str = &metadata.target();
        if let Some(namespacer) = metadata.target().find(':')
        {
            target = prefix(metadata.target(), namespacer);
        }
        
        self.allowed_packages.contains(&String::from(target))
    }
    
    fn log(&self, record : &Record)
    {
        if self.enabled(record.metadata())
        {
            let mut message = record.args().to_string();
            println!("[ {:5} {} ] {}", record.level(), record.target(), message);

            let mut history_borrow = self.history.lock().unwrap();
            message.truncate(history_borrow.max_message_len);
            message.shrink_to_fit();

            history_borrow.add_message(ConsoleHistoryEntry
            {
                level : record.level(),
                source : prefix(record.target(), MAX_SOURCE_LENGTH).to_string(),
                message
            });
        }
    }
    
    fn flush(&self)
    {
    
    }
}