Skip to content

Commit

Permalink
Rollup merge of rust-lang#28991 - goyox86:goyox86/rustfmting-liblog-I…
Browse files Browse the repository at this point in the history
…I, r=alexcrichton

Hi Rustaceans!

This is the second version of running rustfmt on liblog rust-lang#28898. There are only rustfmt suggested changes. Because I think that some patterns here (that I fixed up in the prev PR need to be discussed in detail.

//cc @nrc
  • Loading branch information
Manishearth committed Oct 14, 2015
2 parents 2939666 + 94946db commit 0e969d2
Show file tree
Hide file tree
Showing 2 changed files with 114 additions and 88 deletions.
84 changes: 45 additions & 39 deletions src/liblog/directive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,17 @@ pub struct LogDirective {
pub level: u32,
}

pub const LOG_LEVEL_NAMES: [&'static str; 4] = ["ERROR", "WARN", "INFO",
"DEBUG"];
pub const LOG_LEVEL_NAMES: [&'static str; 4] = ["ERROR", "WARN", "INFO", "DEBUG"];

/// Parse an individual log level that is either a number or a symbolic log level
fn parse_log_level(level: &str) -> Option<u32> {
level.parse::<u32>().ok().or_else(|| {
let pos = LOG_LEVEL_NAMES.iter().position(|&name| name.eq_ignore_ascii_case(level));
pos.map(|p| p as u32 + 1)
}).map(|p| cmp::min(p, ::MAX_LOG_LEVEL))
level.parse::<u32>()
.ok()
.or_else(|| {
let pos = LOG_LEVEL_NAMES.iter().position(|&name| name.eq_ignore_ascii_case(level));
pos.map(|p| p as u32 + 1)
})
.map(|p| cmp::min(p, ::MAX_LOG_LEVEL))
}

/// Parse a logging specification string (e.g: "crate1,crate2::mod3,crate3::x=1/foo")
Expand All @@ -40,44 +42,48 @@ pub fn parse_logging_spec(spec: &str) -> (Vec<LogDirective>, Option<String>) {
let mods = parts.next();
let filter = parts.next();
if parts.next().is_some() {
println!("warning: invalid logging spec '{}', \
ignoring it (too many '/'s)", spec);
println!("warning: invalid logging spec '{}', ignoring it (too many '/'s)",
spec);
return (dirs, None);
}
mods.map(|m| { for s in m.split(',') {
if s.is_empty() { continue }
let mut parts = s.split('=');
let (log_level, name) = match (parts.next(), parts.next().map(|s| s.trim()), parts.next()) {
(Some(part0), None, None) => {
// if the single argument is a log-level string or number,
// treat that as a global fallback
match parse_log_level(part0) {
Some(num) => (num, None),
None => (::MAX_LOG_LEVEL, Some(part0)),
}
mods.map(|m| {
for s in m.split(',') {
if s.is_empty() {
continue
}
(Some(part0), Some(""), None) => (::MAX_LOG_LEVEL, Some(part0)),
(Some(part0), Some(part1), None) => {
match parse_log_level(part1) {
Some(num) => (num, Some(part0)),
_ => {
println!("warning: invalid logging spec '{}', \
ignoring it", part1);
continue
let mut parts = s.split('=');
let (log_level, name) = match (parts.next(),
parts.next().map(|s| s.trim()),
parts.next()) {
(Some(part0), None, None) => {
// if the single argument is a log-level string or number,
// treat that as a global fallback
match parse_log_level(part0) {
Some(num) => (num, None),
None => (::MAX_LOG_LEVEL, Some(part0)),
}
}
},
_ => {
println!("warning: invalid logging spec '{}', \
ignoring it", s);
continue
}
};
dirs.push(LogDirective {
name: name.map(str::to_owned),
level: log_level,
});
}});
(Some(part0), Some(""), None) => (::MAX_LOG_LEVEL, Some(part0)),
(Some(part0), Some(part1), None) => {
match parse_log_level(part1) {
Some(num) => (num, Some(part0)),
_ => {
println!("warning: invalid logging spec '{}', ignoring it", part1);
continue
}
}
}
_ => {
println!("warning: invalid logging spec '{}', ignoring it", s);
continue
}
};
dirs.push(LogDirective {
name: name.map(str::to_owned),
level: log_level,
});
}
});

(dirs, filter.map(str::to_owned))
}
Expand Down
118 changes: 69 additions & 49 deletions src/liblog/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,9 @@ pub trait Logger {
fn log(&mut self, record: &LogRecord);
}

struct DefaultLogger { handle: Stderr }
struct DefaultLogger {
handle: Stderr,
}

/// Wraps the log level with fmt implementations.
#[derive(Copy, Clone, PartialEq, PartialOrd, Debug)]
Expand All @@ -246,7 +248,7 @@ impl fmt::Display for LogLevel {
let LogLevel(level) = *self;
match LOG_LEVEL_NAMES.get(level as usize - 1) {
Some(ref name) => fmt::Display::fmt(name, fmt),
None => fmt::Display::fmt(&level, fmt)
None => fmt::Display::fmt(&level, fmt),
}
}
}
Expand Down Expand Up @@ -301,11 +303,10 @@ pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) {
// Completely remove the local logger from TLS in case anyone attempts to
// frob the slot while we're doing the logging. This will destroy any logger
// set during logging.
let mut logger: Box<Logger + Send> = LOCAL_LOGGER.with(|s| {
s.borrow_mut().take()
}).unwrap_or_else(|| {
box DefaultLogger { handle: io::stderr() }
});
let mut logger: Box<Logger + Send> = LOCAL_LOGGER.with(|s| s.borrow_mut().take())
.unwrap_or_else(|| {
box DefaultLogger { handle: io::stderr() }
});
logger.log(&LogRecord {
level: LogLevel(level),
args: args,
Expand All @@ -320,22 +321,21 @@ pub fn log(level: u32, loc: &'static LogLocation, args: fmt::Arguments) {
/// safely
#[doc(hidden)]
#[inline(always)]
pub fn log_level() -> u32 { unsafe { LOG_LEVEL } }
pub fn log_level() -> u32 {
unsafe { LOG_LEVEL }
}

/// Replaces the thread-local logger with the specified logger, returning the old
/// logger.
pub fn set_logger(logger: Box<Logger + Send>) -> Option<Box<Logger + Send>> {
let mut l = Some(logger);
LOCAL_LOGGER.with(|slot| {
mem::replace(&mut *slot.borrow_mut(), l.take())
})
LOCAL_LOGGER.with(|slot| mem::replace(&mut *slot.borrow_mut(), l.take()))
}

/// A LogRecord is created by the logging macros, and passed as the only
/// argument to Loggers.
#[derive(Debug)]
pub struct LogRecord<'a> {

/// The module path of where the LogRecord originated.
pub module_path: &'a str,

Expand Down Expand Up @@ -373,7 +373,9 @@ pub fn mod_enabled(level: u32, module: &str) -> bool {
// again to whether they should really be here or not. Hence, despite this
// check being expanded manually in the logging macro, this function checks
// the log level again.
if level > unsafe { LOG_LEVEL } { return false }
if level > unsafe { LOG_LEVEL } {
return false
}

// This assertion should never get tripped unless we're in an at_exit
// handler after logging has been torn down and a logging attempt was made.
Expand All @@ -385,14 +387,11 @@ pub fn mod_enabled(level: u32, module: &str) -> bool {
}
}

fn enabled(level: u32,
module: &str,
iter: slice::Iter<directive::LogDirective>)
-> bool {
fn enabled(level: u32, module: &str, iter: slice::Iter<directive::LogDirective>) -> bool {
// Search for the longest match, the vector is assumed to be pre-sorted.
for directive in iter.rev() {
match directive.name {
Some(ref name) if !module.starts_with(&name[..]) => {},
Some(ref name) if !module.starts_with(&name[..]) => {}
Some(..) | None => {
return level <= directive.level
}
Expand Down Expand Up @@ -445,16 +444,14 @@ mod tests {

#[test]
fn match_full_path() {
let dirs = [
LogDirective {
name: Some("crate2".to_string()),
level: 3
},
LogDirective {
name: Some("crate1::mod1".to_string()),
level: 2
}
];
let dirs = [LogDirective {
name: Some("crate2".to_string()),
level: 3,
},
LogDirective {
name: Some("crate1::mod1".to_string()),
level: 2,
}];
assert!(enabled(2, "crate1::mod1", dirs.iter()));
assert!(!enabled(3, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2", dirs.iter()));
Expand All @@ -463,49 +460,72 @@ mod tests {

#[test]
fn no_match() {
let dirs = [
LogDirective { name: Some("crate2".to_string()), level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
let dirs = [LogDirective {
name: Some("crate2".to_string()),
level: 3,
},
LogDirective {
name: Some("crate1::mod1".to_string()),
level: 2,
}];
assert!(!enabled(2, "crate3", dirs.iter()));
}

#[test]
fn match_beginning() {
let dirs = [
LogDirective { name: Some("crate2".to_string()), level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
let dirs = [LogDirective {
name: Some("crate2".to_string()),
level: 3,
},
LogDirective {
name: Some("crate1::mod1".to_string()),
level: 2,
}];
assert!(enabled(3, "crate2::mod1", dirs.iter()));
}

#[test]
fn match_beginning_longest_match() {
let dirs = [
LogDirective { name: Some("crate2".to_string()), level: 3 },
LogDirective { name: Some("crate2::mod".to_string()), level: 4 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
let dirs = [LogDirective {
name: Some("crate2".to_string()),
level: 3,
},
LogDirective {
name: Some("crate2::mod".to_string()),
level: 4,
},
LogDirective {
name: Some("crate1::mod1".to_string()),
level: 2,
}];
assert!(enabled(4, "crate2::mod1", dirs.iter()));
assert!(!enabled(4, "crate2", dirs.iter()));
}

#[test]
fn match_default() {
let dirs = [
LogDirective { name: None, level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 2 }
];
let dirs = [LogDirective {
name: None,
level: 3,
},
LogDirective {
name: Some("crate1::mod1".to_string()),
level: 2,
}];
assert!(enabled(2, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2::mod2", dirs.iter()));
}

#[test]
fn zero_level() {
let dirs = [
LogDirective { name: None, level: 3 },
LogDirective { name: Some("crate1::mod1".to_string()), level: 0 }
];
let dirs = [LogDirective {
name: None,
level: 3,
},
LogDirective {
name: Some("crate1::mod1".to_string()),
level: 0,
}];
assert!(!enabled(1, "crate1::mod1", dirs.iter()));
assert!(enabled(3, "crate2::mod2", dirs.iter()));
}
Expand Down

0 comments on commit 0e969d2

Please sign in to comment.