diff --git a/src/lib.rs b/src/lib.rs index 0dca5e3cc..cf6f09052 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -479,7 +479,7 @@ impl FromStr for Level { impl fmt::Display for Level { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.pad(LOG_LEVEL_NAMES[*self as usize]) + fmt.pad(self.as_str()) } } @@ -506,6 +506,13 @@ impl Level { 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] + } } /// An enum representing the available verbosity level filters of the logger. @@ -632,7 +639,7 @@ impl FromStr for LevelFilter { impl fmt::Display for LevelFilter { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt.pad(LOG_LEVEL_NAMES[*self as usize]) + fmt.pad(self.as_str()) } } @@ -661,6 +668,13 @@ impl LevelFilter { pub fn to_level(&self) -> Option { 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] + } } #[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)] @@ -1496,6 +1510,20 @@ mod tests { } } + #[test] + fn test_level_as_str() { + let tests = &[ + (Level::Error, "ERROR"), + (Level::Warn, "WARN"), + (Level::Info, "INFO"), + (Level::Debug, "DEBUG"), + (Level::Trace, "TRACE"), + ]; + for (input, expected) in tests { + assert_eq!(*expected, input.as_str()); + } + } + #[test] fn test_level_show() { assert_eq!("INFO", Level::Info.to_string()); @@ -1535,6 +1563,21 @@ mod tests { assert_eq!(LevelFilter::Trace, Level::Trace.to_level_filter()); } + #[test] + fn test_level_filter_as_str() { + let tests = &[ + (LevelFilter::Off, "OFF"), + (LevelFilter::Error, "ERROR"), + (LevelFilter::Warn, "WARN"), + (LevelFilter::Info, "INFO"), + (LevelFilter::Debug, "DEBUG"), + (LevelFilter::Trace, "TRACE"), + ]; + for (input, expected) in tests { + assert_eq!(*expected, input.as_str()); + } + } + #[test] #[cfg(feature = "std")] fn test_error_trait() {