pub mod custom {
pub struct LogElement {
time_stamp : Option<std::time::SystemTime>,
title : String,
context : String
}
impl LogElement {
pub fn new(title : &str, context : String, time_stamp_on : bool) -> LogElement {
LogElement {
time_stamp : if time_stamp_on {
Option::Some(std::time::SystemTime::now())
} else {
Option::None
},
title : String::from(title),
context : context
}
}
pub fn new_str(title : &str, context : &str, time_stamp_on : bool) -> LogElement {
LogElement {
time_stamp : if time_stamp_on {
Option::Some(std::time::SystemTime::now())
} else {
Option::None
},
title : String::from(title),
context : String::from(context)
}
}
pub fn to_string(&self, seperator : &char, start : std::time::SystemTime) -> String {
match self.time_stamp {
Some(time) => {
format!(
"[{}]\t{}\t{}\t{}",
match time.duration_since(start.clone()) {
Ok(n) => {
format!(
"{}:{}:{}:{}",
trim_to_1000(n.as_secs() as usize),
trim_to_1000(n.as_millis() as usize),
trim_to_1000(n.as_micros() as usize),
trim_to_1000(n.as_nanos() as usize)
)
},
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
},
&self.title,
seperator,
&self.context
)
},
None => {
format!(
"{}\t{}\t{}",
&self.title,
seperator,
&self.context
)
},
}
}
}
impl Clone for LogElement {
fn clone(&self) -> LogElement {
LogElement::new(&self.title.clone()[..], self.context.clone(), {
match self.time_stamp {
Some(_) => true,
None => false
}
})
}
}
pub struct Log {
time_stamp : bool,
start_time : std::time::SystemTime,
seperator : char,
elements : Vec<LogElement>
}
impl Log {
pub fn new(time_stamp_on : bool, seperate : char) -> Log {
Log {
time_stamp : time_stamp_on,
start_time : std::time::SystemTime::now(),
seperator : seperate,
elements : Vec::new(),
}
}
pub fn add(&mut self, titel : &str, context : String) {
self.elements.push(LogElement::new(titel, context, self.time_stamp));
}
pub fn add_str(&mut self, titel : &str, context : &str) {
self.elements.push(LogElement::new_str(titel, context, self.time_stamp));
}
pub fn save(&self, file_name : &str) {
std::fs::File::create(file_name).expect("Unable to write file");
std::fs::write(file_name, self.to_string()).expect("Unable to write file");
}
pub fn to_string(&self) -> String {
let mut value = String::new();
let mut count = 0_usize;
for element in self.elements.iter() {
let s : String = element.to_string(&self.seperator,self.start_time.clone());
for c in s.chars() {
value.push(c);
}
if count < self.elements.len()-1 {
value.push('\n');
}
count += 1;
}
return value;
}
}
impl Clone for Log {
fn clone(&self) -> Log {
Log::new(self.time_stamp.clone(), self.seperator.clone())
}
}
fn trim_to_1000(n:usize) -> usize {
let mut num = n;
while num > 1000 {
num /= 1000;
}
return num;
}
}