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
use crate::lazy_static::lazy_static;
use std::{fmt::Debug, sync::Mutex};
#[cfg(not(target_arch = "wasm32"))]
use std::io::{self, Write};
#[cfg(target_arch = "wasm32")]
use crate::core::wasm_bindgen::{self, prelude::*};
#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
lazy_static! {
static ref LOG: Mutex<Log> = Mutex::new(Log {
#[cfg(not(target_arch = "wasm32"))]
file: std::fs::File::create("rg3d.log").unwrap(),
verbosity: MessageKind::Information
});
}
#[derive(Copy, Clone, PartialOrd, PartialEq, Eq, Ord, Hash)]
#[repr(u32)]
pub enum MessageKind {
Information = 0,
Warning = 1,
Error = 2,
}
impl MessageKind {
fn as_str(self) -> &'static str {
match self {
MessageKind::Information => "[INFO]: ",
MessageKind::Warning => "[WARNING]: ",
MessageKind::Error => "[ERROR]: ",
}
}
}
pub struct Log {
#[cfg(not(target_arch = "wasm32"))]
file: std::fs::File,
verbosity: MessageKind,
}
impl Log {
fn write_internal(&mut self, kind: MessageKind, mut msg: String) {
if kind as u32 >= self.verbosity as u32 {
msg.insert_str(0, kind.as_str());
#[cfg(target_arch = "wasm32")]
{
log(&msg);
}
#[cfg(not(target_arch = "wasm32"))]
{
let _ = io::stdout().write_all(msg.as_bytes());
let _ = self.file.write_all(msg.as_bytes());
}
}
}
fn writeln_internal(&mut self, kind: MessageKind, mut msg: String) {
msg.push('\n');
self.write_internal(kind, msg)
}
pub fn write(kind: MessageKind, msg: String) {
LOG.lock().unwrap().write_internal(kind, msg);
}
pub fn writeln(kind: MessageKind, msg: String) {
LOG.lock().unwrap().writeln_internal(kind, msg);
}
pub fn set_verbosity(kind: MessageKind) {
LOG.lock().unwrap().verbosity = kind;
}
pub fn verify<E>(result: Result<(), E>)
where
E: Debug,
{
if let Err(e) = result {
Self::writeln(
MessageKind::Error,
format!("Operation failed! Reason: {:?}", e),
);
}
}
}