File size: 1,789 Bytes
d5bfab8 |
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 |
use std::error::Error;
use std::fs::File;
use std::io::Write;
use std::io::LineWriter;
use std::path::Path;
use std::sync::{Arc, Mutex};
trait SimpleLogState {
fn print(&mut self, content: &String) -> Result<(), Box<dyn Error>>;
}
struct StateLineWriter {
line_writer: LineWriter<File>
}
impl SimpleLogState for StateLineWriter {
fn print(&mut self, content: &String) -> Result<(), Box<dyn Error>> {
// Append to a log file
self.line_writer.write_all(content.as_bytes())?;
self.line_writer.flush()?;
Ok(())
}
}
struct StateSink {}
impl SimpleLogState for StateSink {
fn print(&mut self, _content: &String) -> Result<(), Box<dyn Error>> {
// Silently ignores printing
Ok(())
}
}
#[derive(Clone)]
pub struct SimpleLog {
state: Arc<Mutex<dyn SimpleLogState>>,
}
impl SimpleLog {
pub fn new(path: &Path) -> Result<Self, Box<dyn Error>> {
let file = File::create(path)?;
let line_writer: LineWriter<File> = LineWriter::new(file);
let state = StateLineWriter {
line_writer: line_writer
};
let instance = Self {
state: Arc::new(Mutex::new(state))
};
Ok(instance)
}
#[allow(dead_code)]
pub fn sink() -> Self {
let state = StateSink {};
Self {
state: Arc::new(Mutex::new(state))
}
}
pub fn println<I: AsRef<str>>(&self, message: I) {
let content: String = message.as_ref().into();
let content2 = content + "\n";
self.print(&content2).expect("Unable to print");
}
pub fn print(&self, content: &String) -> Result<(), Box<dyn Error>> {
let mut state = self.state.lock().unwrap();
state.print(content)?;
Ok(())
}
}
|