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 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
use std::{cmp, error, fmt, str::FromStr};
use serde::{Deserialize, Serialize};
static LOG_LEVEL_NAMES: [&str; 6] = ["OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE"];
static LEVEL_PARSE_ERROR: &str =
"attempted to convert a string that doesn't match an existing log level";
/// An enum representing the available verbosity levels of the logger.
///
/// Typical usage includes: checking if a certain `Level` is enabled with
/// [`log!`](super::log), and comparing a [`Level`] directly to a
/// [`LevelFilter`](LevelFilter).
#[repr(usize)]
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, Serialize, Deserialize)]
pub enum Level {
/// The "error" level.
///
/// Designates very serious errors.
// This way these line up with the discriminants for [LevelFilter] below
// This works because Rust treats field-less enums the same way as C does:
// https://doc.rust-lang.org/reference/items/enumerations.html#custom-discriminant-values-for-field-less-enumerations
Error = 1,
/// The "warn" level.
///
/// Designates hazardous situations.
Warn,
/// The "info" level.
///
/// Designates useful information.
Info,
/// The "debug" level.
///
/// Designates lower priority information.
Debug,
/// The "trace" level.
///
/// Designates very low priority, often extremely verbose, information.
Trace,
}
impl PartialEq<LevelFilter> for Level {
#[inline]
fn eq(&self, other: &LevelFilter) -> bool {
*self as usize == *other as usize
}
}
impl PartialOrd for Level {
#[inline]
fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
#[inline]
fn lt(&self, other: &Level) -> bool {
(*self as usize) < *other as usize
}
#[inline]
fn le(&self, other: &Level) -> bool {
*self as usize <= *other as usize
}
#[inline]
fn gt(&self, other: &Level) -> bool {
*self as usize > *other as usize
}
#[inline]
fn ge(&self, other: &Level) -> bool {
*self as usize >= *other as usize
}
}
impl PartialOrd<LevelFilter> for Level {
#[inline]
fn partial_cmp(&self, other: &LevelFilter) -> Option<cmp::Ordering> {
Some((*self as usize).cmp(&(*other as usize)))
}
#[inline]
fn lt(&self, other: &LevelFilter) -> bool {
(*self as usize) < *other as usize
}
#[inline]
fn le(&self, other: &LevelFilter) -> bool {
*self as usize <= *other as usize
}
#[inline]
fn gt(&self, other: &LevelFilter) -> bool {
*self as usize > *other as usize
}
#[inline]
fn ge(&self, other: &LevelFilter) -> bool {
*self as usize >= *other as usize
}
}
impl Ord for Level {
#[inline]
fn cmp(&self, other: &Level) -> cmp::Ordering {
(*self as usize).cmp(&(*other as usize))
}
}
// Reimplemented here because std::ascii is not available in libcore
fn eq_ignore_ascii_case(a: &str, b: &str) -> bool {
fn to_ascii_uppercase(c: u8) -> u8 {
if (b'a'..=b'z').contains(&c) {
c - b'a' + b'A'
} else {
c
}
}
if a.len() == b.len() {
a.bytes()
.zip(b.bytes())
.all(|(a, b)| to_ascii_uppercase(a) == to_ascii_uppercase(b))
} else {
false
}
}
impl FromStr for Level {
type Err = ParseLevelError;
fn from_str(level: &str) -> Result<Level, Self::Err> {
LOG_LEVEL_NAMES
.iter()
.position(|&name| eq_ignore_ascii_case(name, level))
.into_iter()
.filter(|&idx| idx != 0)
.map(|idx| Level::from_usize(idx).unwrap())
.next()
.ok_or(ParseLevelError(()))
}
}
impl fmt::Display for Level {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.pad(self.as_str())
}
}
impl Level {
fn from_usize(u: usize) -> Option<Level> {
match u {
1 => Some(Level::Error),
2 => Some(Level::Warn),
3 => Some(Level::Info),
4 => Some(Level::Debug),
5 => Some(Level::Trace),
_ => None,
}
}
/// Returns the most verbose logging level.
#[inline]
pub fn max() -> Level {
Level::Trace
}
/// Converts the [`Level`] to the equivalent [`LevelFilter`].
#[inline]
pub fn to_level_filter(&self) -> LevelFilter {
LevelFilter::from_usize(*self as usize).unwrap()
}
/// Returns the string representation of the [`Level`].
///
/// This returns the same string as the [`fmt::Display`] implementation.
pub fn as_str(&self) -> &'static str {
LOG_LEVEL_NAMES[*self as usize]
}
/// Iterate through all supported logging levels.
///
/// The order of iteration is from more severe to less severe log messages.
///
/// # Examples
///
/// ```
/// use lunatic_log::Level;
///
/// let mut levels = Level::iter();
///
/// assert_eq!(Some(Level::Error), levels.next());
/// assert_eq!(Some(Level::Trace), levels.last());
/// ```
pub fn iter() -> impl Iterator<Item = Self> {
(1..6).map(|i| Self::from_usize(i).unwrap())
}
}
/// An enum representing the available verbosity level filters of the logger.
///
/// A [`LevelFilter`] may be compared directly to a [`Level`].
#[repr(usize)]
#[derive(Clone, Copy, PartialEq, Eq, Debug, Hash, Serialize, Deserialize)]
pub enum LevelFilter {
/// A level lower than all log levels.
Off,
/// Corresponds to the `Error` log level.
Error,
/// Corresponds to the `Warn` log level.
Warn,
/// Corresponds to the `Info` log level.
Info,
/// Corresponds to the `Debug` log level.
Debug,
/// Corresponds to the `Trace` log level.
Trace,
}
impl PartialEq<Level> for LevelFilter {
#[inline]
fn eq(&self, other: &Level) -> bool {
other.eq(self)
}
}
impl PartialOrd for LevelFilter {
#[inline]
fn partial_cmp(&self, other: &LevelFilter) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
#[inline]
fn lt(&self, other: &LevelFilter) -> bool {
(*self as usize) < *other as usize
}
#[inline]
fn le(&self, other: &LevelFilter) -> bool {
*self as usize <= *other as usize
}
#[inline]
fn gt(&self, other: &LevelFilter) -> bool {
*self as usize > *other as usize
}
#[inline]
fn ge(&self, other: &LevelFilter) -> bool {
*self as usize >= *other as usize
}
}
impl PartialOrd<Level> for LevelFilter {
#[inline]
fn partial_cmp(&self, other: &Level) -> Option<cmp::Ordering> {
Some((*self as usize).cmp(&(*other as usize)))
}
#[inline]
fn lt(&self, other: &Level) -> bool {
(*self as usize) < *other as usize
}
#[inline]
fn le(&self, other: &Level) -> bool {
*self as usize <= *other as usize
}
#[inline]
fn gt(&self, other: &Level) -> bool {
*self as usize > *other as usize
}
#[inline]
fn ge(&self, other: &Level) -> bool {
*self as usize >= *other as usize
}
}
impl Ord for LevelFilter {
#[inline]
fn cmp(&self, other: &LevelFilter) -> cmp::Ordering {
(*self as usize).cmp(&(*other as usize))
}
}
impl FromStr for LevelFilter {
type Err = ParseLevelError;
fn from_str(level: &str) -> Result<LevelFilter, Self::Err> {
LOG_LEVEL_NAMES
.iter()
.position(|&name| eq_ignore_ascii_case(name, level))
.map(|p| LevelFilter::from_usize(p).unwrap())
.ok_or(ParseLevelError(()))
}
}
impl fmt::Display for LevelFilter {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.pad(self.as_str())
}
}
impl LevelFilter {
fn from_usize(u: usize) -> Option<LevelFilter> {
match u {
0 => Some(LevelFilter::Off),
1 => Some(LevelFilter::Error),
2 => Some(LevelFilter::Warn),
3 => Some(LevelFilter::Info),
4 => Some(LevelFilter::Debug),
5 => Some(LevelFilter::Trace),
_ => None,
}
}
/// Returns the most verbose logging level filter.
#[inline]
pub fn max() -> LevelFilter {
LevelFilter::Trace
}
/// Converts `self` to the equivalent [`Level`].
///
/// Returns [`None`] if `self` is [`LevelFilter::Off`].
#[inline]
pub fn to_level(&self) -> Option<Level> {
Level::from_usize(*self as usize)
}
/// Returns the string representation of the [`LevelFilter`].
///
/// This returns the same string as the [`fmt::Display`] implementation.
pub fn as_str(&self) -> &'static str {
LOG_LEVEL_NAMES[*self as usize]
}
/// Iterate through all supported filtering levels.
///
/// The order of iteration is from less to more verbose filtering.
///
/// # Examples
///
/// ```
/// use lunatic_log::LevelFilter;
///
/// let mut levels = LevelFilter::iter();
///
/// assert_eq!(Some(LevelFilter::Off), levels.next());
/// assert_eq!(Some(LevelFilter::Trace), levels.last());
/// ```
pub fn iter() -> impl Iterator<Item = Self> {
(0..6).map(|i| Self::from_usize(i).unwrap())
}
}
/// The type returned by [`from_str`] when the string doesn't match any of the log levels.
///
/// [`from_str`]: https://doc.rust-lang.org/std/str/trait.FromStr.html#tymethod.from_str
#[allow(missing_copy_implementations)]
#[derive(Debug, PartialEq)]
pub struct ParseLevelError(());
impl fmt::Display for ParseLevelError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str(LEVEL_PARSE_ERROR)
}
}
// The Error trait is not available in libcore
impl error::Error for ParseLevelError {}