1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-30 04:27:45 +00:00

Merge pull request #793 from ebfe/clippy

Fix clippy warnings
This commit is contained in:
Alex Lyon 2016-01-06 00:56:07 -08:00
commit 027e02db8b
77 changed files with 436 additions and 505 deletions

View file

@ -89,19 +89,19 @@ fn strip_dir(fullname: &str) -> String {
// Convert to path buffer and get last path component // Convert to path buffer and get last path component
let pb = PathBuf::from(path); let pb = PathBuf::from(path);
match pb.components().last() { match pb.components().last() {
Some(c) => c.as_os_str().to_str().unwrap().to_string(), Some(c) => c.as_os_str().to_str().unwrap().to_owned(),
None => "".to_string() None => "".to_owned()
} }
} }
fn strip_suffix(name: &str, suffix: &str) -> String { fn strip_suffix(name: &str, suffix: &str) -> String {
if name == suffix { if name == suffix {
return name.to_string(); return name.to_owned();
} }
if name.ends_with(suffix) { if name.ends_with(suffix) {
return name[..name.len() - suffix.len()].to_string(); return name[..name.len() - suffix.len()].to_owned();
} }
name.to_string() name.to_owned()
} }

View file

@ -66,16 +66,16 @@ pub fn uumain(args: Vec<String>) -> i32 {
} else { } else {
NumberingMode::NumberNone NumberingMode::NumberNone
}; };
let show_nonprint = matches.opts_present(&["A".to_string(), "e".to_string(), let show_nonprint = matches.opts_present(&["A".to_owned(), "e".to_owned(),
"t".to_string(), "v".to_string()]); "t".to_owned(), "v".to_owned()]);
let show_ends = matches.opts_present(&["E".to_string(), "A".to_string(), let show_ends = matches.opts_present(&["E".to_owned(), "A".to_owned(),
"e".to_string()]); "e".to_owned()]);
let show_tabs = matches.opts_present(&["A".to_string(), "T".to_string(), let show_tabs = matches.opts_present(&["A".to_owned(), "T".to_owned(),
"t".to_string()]); "t".to_owned()]);
let squeeze_blank = matches.opt_present("s"); let squeeze_blank = matches.opt_present("s");
let mut files = matches.free; let mut files = matches.free;
if files.is_empty() { if files.is_empty() {
files.push("-".to_string()); files.push("-".to_owned());
} }
exec(files, number_mode, show_nonprint, show_ends, show_tabs, squeeze_blank); exec(files, number_mode, show_nonprint, show_ends, show_tabs, squeeze_blank);

View file

@ -100,7 +100,7 @@ Each MODE is of the form '[ugoa]*([-+=]([rwxXst]*|[ugo]))+|[-+=]?[0-7]+'.",
fn chmod(files: Vec<String>, changes: bool, quiet: bool, verbose: bool, preserve_root: bool, recursive: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> { fn chmod(files: Vec<String>, changes: bool, quiet: bool, verbose: bool, preserve_root: bool, recursive: bool, fmode: Option<libc::mode_t>, cmode: Option<&String>) -> Result<(), i32> {
let mut r = Ok(()); let mut r = Ok(());
for filename in files.iter() { for filename in &files {
let filename = &filename[..]; let filename = &filename[..];
let file = Path::new(filename); let file = Path::new(filename);
if file.exists() { if file.exists() {
@ -120,7 +120,7 @@ fn chmod(files: Vec<String>, changes: bool, quiet: bool, verbose: bool, preserve
// to chmod() and chmod_file(). // to chmod() and chmod_file().
r = chmod(walk_dir.filter_map(|x| match x { r = chmod(walk_dir.filter_map(|x| match x {
Ok(o) => match o.path().into_os_string().to_str() { Ok(o) => match o.path().into_os_string().to_str() {
Some(s) => Some(s.to_string()), Some(s) => Some(s.to_owned()),
None => None, None => None,
}, },
Err(_) => None, Err(_) => None,
@ -211,7 +211,7 @@ fn parse_numeric(fperm: libc::mode_t, mut mode: &str) -> Result<libc::mode_t, St
_ => unreachable!() _ => unreachable!()
}) })
} }
Err(err) => Err(err.description().to_string()) Err(err) => Err(err.description().to_owned())
} }
} }
} }
@ -265,7 +265,7 @@ fn parse_op(mode: &str, default: Option<char>) -> Result<(char, usize), String>
None => Err(format!("invalid operator (expected +, -, or =, but found {})", ch)) None => Err(format!("invalid operator (expected +, -, or =, but found {})", ch))
} }
}, },
None => Err("unexpected end of mode".to_string()) None => Err("unexpected end of mode".to_owned())
} }
} }

View file

@ -65,7 +65,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
if matches.opt_present("V") { version(); return 0 } if matches.opt_present("V") { version(); return 0 }
if matches.opt_present("h") { help_menu(opts); return 0 } if matches.opt_present("h") { help_menu(opts); return 0 }
if matches.free.len() == 0 { if matches.free.is_empty() {
println!("Missing operand: NEWROOT"); println!("Missing operand: NEWROOT");
println!("Try `{} --help` for more information.", NAME); println!("Try `{} --help` for more information.", NAME);
return 1 return 1
@ -191,7 +191,7 @@ fn set_groups_from_str(groups: &str) {
fn set_user(user: &str) { fn set_user(user: &str) {
if !user.is_empty() { if !user.is_empty() {
let user_id = get_pw_from_args(&vec!(user.to_string())).unwrap().pw_uid; let user_id = get_pw_from_args(&vec!(user.to_owned())).unwrap().pw_uid;
let err = unsafe { setuid(user_id as libc::uid_t) }; let err = unsafe { setuid(user_id as libc::uid_t) };
if err != 0 { if err != 0 {
crash!(1, "cannot set user to {}: {}", user, Error::last_os_error()) crash!(1, "cannot set user to {}: {}", user, Error::last_os_error())

View file

@ -116,7 +116,7 @@ Print CRC and size for each file.", NAME, VERSION);
} }
let mut exit_code = 0; let mut exit_code = 0;
for fname in files.iter() { for fname in &files {
match cksum(fname.as_ref()) { match cksum(fname.as_ref()) {
Ok((crc, size)) => println!("{} {} {}", crc, size, fname), Ok((crc, size)) => println!("{} {} {}", crc, size, fname),
Err(err) => { Err(err) => {

View file

@ -24,7 +24,7 @@ fn mkdelim(col: usize, opts: &getopts::Matches) -> String {
let mut s = String::new(); let mut s = String::new();
let delim = match opts.opt_str("output-delimiter") { let delim = match opts.opt_str("output-delimiter") {
Some(d) => d.clone(), Some(d) => d.clone(),
None => "\t".to_string(), None => "\t".to_owned(),
}; };
if col > 1 && !opts.opt_present("1") { if col > 1 && !opts.opt_present("1") {
@ -51,9 +51,9 @@ enum LineReader {
impl LineReader { impl LineReader {
fn read_line(&mut self, buf: &mut String) -> io::Result<usize> { fn read_line(&mut self, buf: &mut String) -> io::Result<usize> {
match self { match *self {
&mut LineReader::Stdin(ref mut r) => r.read_line(buf), LineReader::Stdin(ref mut r) => r.read_line(buf),
&mut LineReader::FileIn(ref mut r) => r.read_line(buf), LineReader::FileIn(ref mut r) => r.read_line(buf),
} }
} }
} }

View file

@ -66,7 +66,7 @@ fn version() {
println!("{} {}", NAME, VERSION); println!("{} {}", NAME, VERSION);
} }
fn help(usage: &String) { fn help(usage: &str) {
let msg = format!("{0} {1}\n\n\ let msg = format!("{0} {1}\n\n\
Usage: {0} SOURCE DEST\n \ Usage: {0} SOURCE DEST\n \
or: {0} SOURCE... DIRECTORY\n \ or: {0} SOURCE... DIRECTORY\n \
@ -82,7 +82,7 @@ fn copy(matches: getopts::Matches) {
panic!() panic!()
} else { } else {
// All but the last argument: // All but the last argument:
matches.free[..matches.free.len() - 1].iter().map(|arg| arg.clone()).collect() matches.free[..matches.free.len() - 1].iter().cloned().collect()
}; };
let dest = if matches.free.len() < 2 { let dest = if matches.free.len() < 2 {
show_error!("Missing DEST argument. Try --help."); show_error!("Missing DEST argument. Try --help.");
@ -123,7 +123,7 @@ fn copy(matches: getopts::Matches) {
panic!(); panic!();
} }
for src in sources.iter() { for src in &sources {
let source = Path::new(&src); let source = Path::new(&src);
if !source.is_file() { if !source.is_file() {

View file

@ -77,13 +77,10 @@ impl<R: Read> ByteReader<R> {
Err(e) => crash!(1, "read error: {}", e), Err(e) => crash!(1, "read error: {}", e),
}; };
match filled_buf.iter().position(|byte| *byte == b'\n') { if let Some(idx) = filled_buf.iter().position(|byte| *byte == b'\n') {
Some(idx) => { consume_val = idx + 1;
consume_val = idx + 1; bytes_consumed += consume_val;
bytes_consumed += consume_val; break;
break;
}
_ => ()
} }
consume_val = filled_buf.len(); consume_val = filled_buf.len();
@ -94,7 +91,7 @@ impl<R: Read> ByteReader<R> {
} }
self.consume(consume_val); self.consume(consume_val);
return bytes_consumed; bytes_consumed
} }
} }

View file

@ -53,7 +53,7 @@ fn list_to_ranges(list: &str, complement: bool) -> Result<Vec<Range>, String> {
} }
} }
fn cut_bytes<R: Read>(reader: R, ranges: &Vec<Range>, opts: &Options) -> i32 { fn cut_bytes<R: Read>(reader: R, ranges: &[Range], opts: &Options) -> i32 {
use buffer::Bytes::Select; use buffer::Bytes::Select;
use buffer::Bytes::Selected::*; use buffer::Bytes::Selected::*;
@ -125,7 +125,7 @@ fn cut_bytes<R: Read>(reader: R, ranges: &Vec<Range>, opts: &Options) -> i32 {
0 0
} }
fn cut_characters<R: Read>(reader: R, ranges: &Vec<Range>, opts: &Options) -> i32 { fn cut_characters<R: Read>(reader: R, ranges: &[Range], opts: &Options) -> i32 {
let mut buf_in = BufReader::new(reader); let mut buf_in = BufReader::new(reader);
let mut out = stdout(); let mut out = stdout();
let mut buffer = String::new(); let mut buffer = String::new();
@ -135,7 +135,7 @@ fn cut_characters<R: Read>(reader: R, ranges: &Vec<Range>, opts: &Options) -> i3
match buf_in.read_line(&mut buffer) { match buf_in.read_line(&mut buffer) {
Ok(n) if n == 0 => break, Ok(n) if n == 0 => break,
Err(e) => { Err(e) => {
if buffer.len() == 0 { if buffer.is_empty() {
crash!(1, "read error: {}", e); crash!(1, "read error: {}", e);
} }
}, },
@ -195,7 +195,7 @@ fn cut_characters<R: Read>(reader: R, ranges: &Vec<Range>, opts: &Options) -> i3
0 0
} }
fn cut_fields_delimiter<R: Read>(reader: R, ranges: &Vec<Range>, delim: &String, only_delimited: bool, out_delim: &String) -> i32 { fn cut_fields_delimiter<R: Read>(reader: R, ranges: &[Range], delim: &str, only_delimited: bool, out_delim: &str) -> i32 {
let mut buf_in = BufReader::new(reader); let mut buf_in = BufReader::new(reader);
let mut out = stdout(); let mut out = stdout();
let mut buffer = Vec::new(); let mut buffer = Vec::new();
@ -205,7 +205,7 @@ fn cut_fields_delimiter<R: Read>(reader: R, ranges: &Vec<Range>, delim: &String,
match buf_in.read_until(b'\n', &mut buffer) { match buf_in.read_until(b'\n', &mut buffer) {
Ok(n) if n == 0 => break, Ok(n) if n == 0 => break,
Err(e) => { Err(e) => {
if buffer.len() == 0 { if buffer.is_empty() {
crash!(1, "read error: {}", e); crash!(1, "read error: {}", e);
} }
}, },
@ -273,7 +273,7 @@ fn cut_fields_delimiter<R: Read>(reader: R, ranges: &Vec<Range>, delim: &String,
0 0
} }
fn cut_fields<R: Read>(reader: R, ranges: &Vec<Range>, opts: &FieldOptions) -> i32 { fn cut_fields<R: Read>(reader: R, ranges: &[Range], opts: &FieldOptions) -> i32 {
match opts.out_delimeter { match opts.out_delimeter {
Some(ref o_delim) => { Some(ref o_delim) => {
return cut_fields_delimiter(reader, ranges, &opts.delimiter, return cut_fields_delimiter(reader, ranges, &opts.delimiter,
@ -291,7 +291,7 @@ fn cut_fields<R: Read>(reader: R, ranges: &Vec<Range>, opts: &FieldOptions) -> i
match buf_in.read_until(b'\n', &mut buffer) { match buf_in.read_until(b'\n', &mut buffer) {
Ok(n) if n == 0 => break, Ok(n) if n == 0 => break,
Err(e) => { Err(e) => {
if buffer.len() == 0 { if buffer.is_empty() {
crash!(1, "read error: {}", e); crash!(1, "read error: {}", e);
} }
}, },
@ -362,9 +362,9 @@ fn cut_files(mut filenames: Vec<String>, mode: Mode) -> i32 {
let mut stdin_read = false; let mut stdin_read = false;
let mut exit_code = 0; let mut exit_code = 0;
if filenames.len() == 0 { filenames.push("-".to_string()); } if filenames.is_empty() { filenames.push("-".to_owned()); }
for filename in filenames.iter() { for filename in &filenames {
if filename == "-" { if filename == "-" {
if stdin_read { continue } if stdin_read { continue }
@ -469,8 +469,8 @@ pub fn uumain(args: Vec<String>) -> i32 {
{ {
let out_delim = match matches.opt_str("output-delimiter") { let out_delim = match matches.opt_str("output-delimiter") {
Some(s) => { Some(s) => {
if s.len() == 0 { if s.is_empty() {
Some("\0".to_string()) Some("\0".to_owned())
} else { } else {
Some(s) Some(s)
} }
@ -483,10 +483,10 @@ pub fn uumain(args: Vec<String>) -> i32 {
match matches.opt_str("delimiter") { match matches.opt_str("delimiter") {
Some(delim) => { Some(delim) => {
if delim.chars().count() > 1 { if delim.chars().count() > 1 {
Err("the delimiter must be a single character, or the empty string for null".to_string()) Err("the delimiter must be a single character, or the empty string for null".to_owned())
} else { } else {
let delim = if delim.len() == 0 { let delim = if delim.is_empty() {
"\0".to_string() "\0".to_owned()
} else { } else {
delim delim
}; };
@ -501,7 +501,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
} }
None => Ok(Mode::Fields(ranges, None => Ok(Mode::Fields(ranges,
FieldOptions { FieldOptions {
delimiter: "\t".to_string(), delimiter: "\t".to_owned(),
out_delimeter: out_delim, out_delimeter: out_delim,
only_delimited: only_delimited only_delimited: only_delimited
})) }))
@ -510,9 +510,9 @@ pub fn uumain(args: Vec<String>) -> i32 {
) )
} }
(ref b, ref c, ref f) if b.is_some() || c.is_some() || f.is_some() => { (ref b, ref c, ref f) if b.is_some() || c.is_some() || f.is_some() => {
Err("only one type of list may be specified".to_string()) Err("only one type of list may be specified".to_owned())
} }
_ => Err("you must specify a list of bytes, characters, or fields".to_string()) _ => Err("you must specify a list of bytes, characters, or fields".to_owned())
}; };
let mode_parse = match mode_parse { let mode_parse = match mode_parse {
@ -520,9 +520,9 @@ pub fn uumain(args: Vec<String>) -> i32 {
Ok(mode) => { Ok(mode) => {
match mode { match mode {
Mode::Bytes(_, _) | Mode::Characters(_, _) if matches.opt_present("delimiter") => Mode::Bytes(_, _) | Mode::Characters(_, _) if matches.opt_present("delimiter") =>
Err("an input delimiter may be specified only when operating on fields".to_string()), Err("an input delimiter may be specified only when operating on fields".to_owned()),
Mode::Bytes(_, _) | Mode::Characters(_, _) if matches.opt_present("only-delimited") => Mode::Bytes(_, _) | Mode::Characters(_, _) if matches.opt_present("only-delimited") =>
Err("suppressing non-delimited lines makes sense only when operating on fields".to_string()), Err("suppressing non-delimited lines makes sense only when operating on fields".to_owned()),
_ => Ok(mode), _ => Ok(mode),
} }
} }

View file

@ -97,7 +97,7 @@ impl Range {
} }
} }
pub fn complement(ranges: &Vec<Range>) -> Vec<Range> { pub fn complement(ranges: &[Range]) -> Vec<Range> {
use std::usize; use std::usize;
let mut complements = Vec::with_capacity(ranges.len() + 1); let mut complements = Vec::with_capacity(ranges.len() + 1);

View file

@ -46,13 +46,10 @@ directory).", NAME, VERSION);
return 0; return 0;
} }
let separator = match matches.opt_present("zero") { let separator = if matches.opt_present("zero") {"\0"} else {"\n"};
true => "\0",
false => "\n"
};
if !matches.free.is_empty() { if !matches.free.is_empty() {
for path in matches.free.iter() { for path in &matches.free {
let p = Path::new(path); let p = Path::new(path);
match p.parent() { match p.parent() {
Some(d) => { Some(d) => {

View file

@ -101,7 +101,7 @@ fn du(path: &PathBuf, mut my_stat: Stat, options: Arc<Options>, depth: usize) ->
} }
} }
for rx in futures.iter_mut() { for rx in &mut futures {
for stat in rx.recv().unwrap().into_iter().rev() { for stat in rx.recv().unwrap().into_iter().rev() {
if !options.separate_dirs && stat.path.parent().unwrap().to_path_buf() == my_stat.path { if !options.separate_dirs && stat.path.parent().unwrap().to_path_buf() == my_stat.path {
my_stat.size += stat.size; my_stat.size += stat.size;
@ -236,24 +236,18 @@ ers of 1000).",
let options = Options { let options = Options {
all: matches.opt_present("all"), all: matches.opt_present("all"),
program_name: NAME.to_string(), program_name: NAME.to_owned(),
max_depth: max_depth, max_depth: max_depth,
total: matches.opt_present("total"), total: matches.opt_present("total"),
separate_dirs: matches.opt_present("S"), separate_dirs: matches.opt_present("S"),
}; };
let strs = if matches.free.is_empty() {vec!("./".to_string())} else {matches.free.clone()}; let strs = if matches.free.is_empty() {vec!("./".to_owned())} else {matches.free.clone()};
let options_arc = Arc::new(options); let options_arc = Arc::new(options);
let MB = match matches.opt_present("si") { let MB = if matches.opt_present("si") {1000 * 1000} else {1024 * 1024};
true => 1000 * 1000, let KB = if matches.opt_present("si") {1000} else {1024};
false => 1024 * 1024,
};
let KB = match matches.opt_present("si") {
true => 1000,
false => 1024,
};
let block_size = match matches.opt_str("block-size") { let block_size = match matches.opt_str("block-size") {
Some(s) => { Some(s) => {
@ -331,10 +325,7 @@ Try '{} --help' for more information.", s, NAME);
None => "%Y-%m-%d %H:%M" None => "%Y-%m-%d %H:%M"
}; };
let line_separator = match matches.opt_present("0") { let line_separator = if matches.opt_present("0") {"\0"} else {"\n"};
true => "\0",
false => "\n",
};
let mut grand_total = 0; let mut grand_total = 0;
for path_str in strs.into_iter() { for path_str in strs.into_iter() {
@ -343,11 +334,12 @@ Try '{} --help' for more information.", s, NAME);
let (_, len) = iter.size_hint(); let (_, len) = iter.size_hint();
let len = len.unwrap(); let len = len.unwrap();
for (index, stat) in iter.enumerate() { for (index, stat) in iter.enumerate() {
let size = match matches.opt_present("apparent-size") { let size = if matches.opt_present("apparent-size") {
true => stat.nlink * stat.size, stat.nlink * stat.size
} else {
// C's stat is such that each block is assume to be 512 bytes // C's stat is such that each block is assume to be 512 bytes
// See: http://linux.die.net/man/2/stat // See: http://linux.die.net/man/2/stat
false => stat.blocks * 512, stat.blocks * 512
}; };
if matches.opt_present("time") { if matches.opt_present("time") {
let tm = { let tm = {

View file

@ -29,7 +29,7 @@ struct EchoOptions {
} }
#[inline(always)] #[inline(always)]
fn to_char(bytes: &Vec<u8>, base: u32) -> char { fn to_char(bytes: &[u8], base: u32) -> char {
usize::from_str_radix(from_utf8(bytes.as_ref()).unwrap(), base).unwrap() as u8 as char usize::from_str_radix(from_utf8(bytes.as_ref()).unwrap(), base).unwrap() as u8 as char
} }
@ -70,7 +70,7 @@ fn convert_str(string: &[u8], index: usize, base: u32) -> (char, usize) {
} }
} }
if bytes.len() == 0 { if bytes.is_empty() {
(' ', 0) (' ', 0)
} else { } else {
(to_char(&bytes, base), bytes.len()) (to_char(&bytes, base), bytes.len())
@ -177,65 +177,60 @@ pub fn uumain(args: Vec<String>) -> i32 {
if options.escape { if options.escape {
let mut prev_was_slash = false; let mut prev_was_slash = false;
let mut iter = string.chars().enumerate(); let mut iter = string.chars().enumerate();
loop { while let Some((index, c)) = iter.next() {
match iter.next() { if !prev_was_slash {
Some((index, c)) => { if c != '\\' {
if !prev_was_slash { print!("{}", c);
if c != '\\' { } else {
print!("{}", c); prev_was_slash = true;
}
} else {
prev_was_slash = false;
match c {
'\\' => print!("\\"),
'a' => print!("\x07"),
'b' => print!("\x08"),
'c' => break,
'e' => print!("\x1B"),
'f' => print!("\x0C"),
'n' => print!("\n"),
'r' => print!("\r"),
't' => print!("\t"),
'v' => print!("\x0B"),
'x' => {
let (c, num_char_used) = convert_str(string.as_bytes(), index + 1, 16);
if num_char_used == 0 {
print!("\\x");
} else { } else {
prev_was_slash = true; print!("{}", c);
} for _ in 0 .. num_char_used {
} else { iter.next(); // consume used characters
prev_was_slash = false;
match c {
'\\' => print!("\\"),
'a' => print!("\x07"),
'b' => print!("\x08"),
'c' => break,
'e' => print!("\x1B"),
'f' => print!("\x0C"),
'n' => print!("\n"),
'r' => print!("\r"),
't' => print!("\t"),
'v' => print!("\x0B"),
'x' => {
let (c, num_char_used) = convert_str(string.as_bytes(), index + 1, 16);
if num_char_used == 0 {
print!("\\x");
} else {
print!("{}", c);
for _ in 0 .. num_char_used {
iter.next(); // consume used characters
}
}
},
'0' => {
let (c, num_char_used) = convert_str(string.as_bytes(), index + 1, 8);
if num_char_used == 0 {
print!("\0");
} else {
print!("{}", c);
for _ in 0 .. num_char_used {
iter.next(); // consume used characters
}
}
} }
_ => { }
let (esc_c, num_char_used) = convert_str(string.as_bytes(), index, 8); },
if num_char_used == 0 { '0' => {
print!("\\{}", c); let (c, num_char_used) = convert_str(string.as_bytes(), index + 1, 8);
} else { if num_char_used == 0 {
print!("{}", esc_c); print!("\0");
for _ in 1 .. num_char_used { } else {
iter.next(); // consume used characters print!("{}", c);
} for _ in 0 .. num_char_used {
} iter.next(); // consume used characters
}
}
}
_ => {
let (esc_c, num_char_used) = convert_str(string.as_bytes(), index, 8);
if num_char_used == 0 {
print!("\\{}", c);
} else {
print!("{}", esc_c);
for _ in 1 .. num_char_used {
iter.next(); // consume used characters
} }
} }
} }
} }
None => break
} }
} }
} else { } else {

18
src/env/env.rs vendored
View file

@ -84,11 +84,11 @@ pub fn uumain(args: Vec<String>) -> i32 {
match (name, value) { match (name, value) {
(Some(n), Some(v)) => { (Some(n), Some(v)) => {
opts.sets.push((n.to_string(), v.to_string())); opts.sets.push((n.to_owned(), v.to_owned()));
} }
_ => { _ => {
// read the program now // read the program now
opts.program.push(opt.to_string()); opts.program.push(opt.to_owned());
break; break;
} }
} }
@ -104,7 +104,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
match var { match var {
None => println!("{}: this option requires an argument: {}", NAME, opt), None => println!("{}: this option requires an argument: {}", NAME, opt),
Some(s) => opts.unsets.push(s.to_string()) Some(s) => opts.unsets.push(s.to_owned())
} }
} }
@ -137,7 +137,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
match var { match var {
None => println!("{}: this option requires an argument: {}", NAME, opt), None => println!("{}: this option requires an argument: {}", NAME, opt),
Some(s) => opts.unsets.push(s.to_string()) Some(s) => opts.unsets.push(s.to_owned())
} }
} }
_ => { _ => {
@ -156,12 +156,12 @@ pub fn uumain(args: Vec<String>) -> i32 {
match (name, value) { match (name, value) {
(Some(n), Some(v)) => { (Some(n), Some(v)) => {
// yes // yes
opts.sets.push((n.to_string(), v.to_string())); opts.sets.push((n.to_owned(), v.to_owned()));
wait_cmd = true; wait_cmd = true;
} }
// no, its a program-like opt // no, its a program-like opt
_ => { _ => {
opts.program.push(opt.to_string()); opts.program.push(opt.clone());
break; break;
} }
} }
@ -172,7 +172,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
// read program arguments // read program arguments
for opt in iter { for opt in iter {
opts.program.push(opt.to_string()); opts.program.push(opt.clone());
} }
if opts.ignore_env { if opts.ignore_env {
@ -181,11 +181,11 @@ pub fn uumain(args: Vec<String>) -> i32 {
} }
} }
for name in opts.unsets.iter() { for name in &opts.unsets {
env::remove_var(name); env::remove_var(name);
} }
for &(ref name, ref val) in opts.sets.iter() { for &(ref name, ref val) in &opts.sets {
env::set_var(name, val); env::set_var(name, val);
} }

View file

@ -46,9 +46,8 @@ fn tabstops_parse(s: String) -> Vec<usize> {
crash!(1, "{}\n", "tab size cannot be 0"); crash!(1, "{}\n", "tab size cannot be 0");
} }
match nums.iter().fold((true, 0), |(acc, last), &n| (acc && last <= n, n)) { if let (false, _) = nums.iter().fold((true, 0), |(acc, last), &n| (acc && last <= n, n)) {
(false, _) => crash!(1, "{}\n", "tab sizes must be ascending"), crash!(1, "{}\n", "tab sizes must be ascending");
_ => {}
} }
nums nums
@ -83,7 +82,7 @@ impl Options {
let files = let files =
if matches.free.is_empty() { if matches.free.is_empty() {
vec!("-".to_string()) vec!("-".to_owned())
} else { } else {
matches.free matches.free
}; };
@ -168,7 +167,7 @@ fn expand(options: Options) {
while match fh.read_until('\n' as u8, &mut buf) { while match fh.read_until('\n' as u8, &mut buf) {
Ok(s) => s > 0, Ok(s) => s > 0,
Err(_) => buf.len() > 0, Err(_) => buf.is_empty(),
} { } {
let mut col = 0; let mut col = 0;
let mut byte = 0; let mut byte = 0;

View file

@ -41,9 +41,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
fn process_expr( token_strings: &Vec<String> ) -> Result< String, String > { fn process_expr( token_strings: &Vec<String> ) -> Result< String, String > {
let maybe_tokens = tokens::strings_to_tokens( &token_strings ); let maybe_tokens = tokens::strings_to_tokens( &token_strings );
let maybe_ast = syntax_tree::tokens_to_ast( maybe_tokens ); let maybe_ast = syntax_tree::tokens_to_ast( maybe_tokens );
let maybe_result = evaluate_ast( maybe_ast ); evaluate_ast( maybe_ast )
maybe_result
} }
fn print_expr_ok( expr_result: &String ) -> i32 { fn print_expr_ok( expr_result: &String ) -> i32 {

View file

@ -30,9 +30,9 @@ impl ASTNode {
for _ in 0..depth { for _ in 0..depth {
print!("\t", ); print!("\t", );
} }
match self { match *self {
&ASTNode::Leaf{ ref token_idx, ref value } => println!("Leaf( {} ) at #{} ( evaluate -> {:?} )", value, token_idx, self.evaluate()), ASTNode::Leaf{ ref token_idx, ref value } => println!("Leaf( {} ) at #{} ( evaluate -> {:?} )", value, token_idx, self.evaluate()),
&ASTNode::Node{ ref token_idx, ref op_type, ref operands } => { ASTNode::Node{ ref token_idx, ref op_type, ref operands } => {
println!("Node( {} ) at #{} (evaluate -> {:?})", op_type, token_idx, self.evaluate()); println!("Node( {} ) at #{} (evaluate -> {:?})", op_type, token_idx, self.evaluate());
for operand in operands { for operand in operands {
operand.debug_dump_impl( depth + 1 ); operand.debug_dump_impl( depth + 1 );
@ -52,9 +52,9 @@ impl ASTNode {
Box::new( ASTNode::Leaf{ token_idx: token_idx, value: value.clone() } ) Box::new( ASTNode::Leaf{ token_idx: token_idx, value: value.clone() } )
} }
pub fn evaluate( &self ) -> Result<String, String> { pub fn evaluate( &self ) -> Result<String, String> {
match self { match *self {
&ASTNode::Leaf{ ref value, .. } => Ok( value.clone() ), ASTNode::Leaf{ ref value, .. } => Ok( value.clone() ),
&ASTNode::Node{ ref op_type, .. } => ASTNode::Node{ ref op_type, .. } =>
match self.operand_values() { match self.operand_values() {
Err( reason ) => Err( reason ), Err( reason ) => Err( reason ),
Ok( operand_values ) => Ok( operand_values ) =>
@ -64,12 +64,12 @@ impl ASTNode {
"*" => infix_operator_two_ints( |a: i64, b: i64| Ok( a * b ), &operand_values ), "*" => infix_operator_two_ints( |a: i64, b: i64| Ok( a * b ), &operand_values ),
"/" => infix_operator_two_ints( "/" => infix_operator_two_ints(
|a: i64, b: i64| |a: i64, b: i64|
if b == 0 { Err("division by zero".to_string()) } if b == 0 { Err("division by zero".to_owned()) }
else { Ok( a / b ) }, else { Ok( a / b ) },
&operand_values ), &operand_values ),
"%" => infix_operator_two_ints( "%" => infix_operator_two_ints(
|a: i64, b: i64| |a: i64, b: i64|
if b == 0 { Err("division by zero".to_string()) } if b == 0 { Err("division by zero".to_owned()) }
else { Ok( a % b ) }, else { Ok( a % b ) },
&operand_values ), &operand_values ),
@ -149,7 +149,7 @@ pub fn tokens_to_ast( maybe_tokens: Result< Vec<(usize, Token)>, String > ) -> R
maybe_dump_rpn( &out_stack ); maybe_dump_rpn( &out_stack );
let result = ast_from_rpn( &mut out_stack ); let result = ast_from_rpn( &mut out_stack );
if !out_stack.is_empty() { if !out_stack.is_empty() {
Err( "syntax error (fist RPN token does not represent expression AST's root)".to_string() ) Err( "syntax error (fist RPN token does not represent expression AST's root)".to_owned() )
} }
else { else {
maybe_dump_ast( &result ); maybe_dump_ast( &result );
@ -163,9 +163,9 @@ fn maybe_dump_ast( result: &Result< Box<ASTNode>, String > ) {
if let Ok( debug_var ) = env::var( "EXPR_DEBUG_AST" ) { if let Ok( debug_var ) = env::var( "EXPR_DEBUG_AST" ) {
if debug_var == "1" { if debug_var == "1" {
println!("EXPR_DEBUG_AST"); println!("EXPR_DEBUG_AST");
match result { match *result {
&Ok( ref ast ) => ast.debug_dump(), Ok( ref ast ) => ast.debug_dump(),
&Err( ref reason ) => println!("\terr: {:?}", reason), Err( ref reason ) => println!("\terr: {:?}", reason),
} }
} }
} }
@ -185,7 +185,7 @@ fn maybe_dump_rpn( rpn: &TokenStack ) {
fn ast_from_rpn( rpn: &mut TokenStack ) -> Result<Box<ASTNode>, String> { fn ast_from_rpn( rpn: &mut TokenStack ) -> Result<Box<ASTNode>, String> {
match rpn.pop() { match rpn.pop() {
None => Err( "syntax error (premature end of expression)".to_string() ), None => Err( "syntax error (premature end of expression)".to_owned() ),
Some( (token_idx, Token::Value{ value }) ) => Some( (token_idx, Token::Value{ value }) ) =>
Ok( ASTNode::new_leaf( token_idx, &value ) ), Ok( ASTNode::new_leaf( token_idx, &value ) ),
@ -225,18 +225,18 @@ fn move_rest_of_ops_to_out( out_stack: &mut TokenStack, op_stack: &mut TokenStac
fn push_token_to_either_stack( token_idx: usize, token: &Token, out_stack: &mut TokenStack, op_stack: &mut TokenStack ) -> Result<(), String> { fn push_token_to_either_stack( token_idx: usize, token: &Token, out_stack: &mut TokenStack, op_stack: &mut TokenStack ) -> Result<(), String> {
let result = let result =
match token { match *token {
&Token::Value{ .. } => Ok( out_stack.push( (token_idx, token.clone()) ) ), Token::Value{ .. } => Ok( out_stack.push( (token_idx, token.clone()) ) ),
&Token::InfixOp{ .. } => Token::InfixOp{ .. } =>
if op_stack.is_empty() { Ok( op_stack.push( (token_idx, token.clone()) ) ) } if op_stack.is_empty() { Ok( op_stack.push( (token_idx, token.clone()) ) ) }
else { push_op_to_stack( token_idx, token, out_stack, op_stack ) }, else { push_op_to_stack( token_idx, token, out_stack, op_stack ) },
&Token::PrefixOp{ .. } => Ok( op_stack.push( (token_idx, token.clone()) ) ), Token::PrefixOp{ .. } => Ok( op_stack.push( (token_idx, token.clone()) ) ),
&Token::ParOpen => Ok( op_stack.push( (token_idx, token.clone()) ) ), Token::ParOpen => Ok( op_stack.push( (token_idx, token.clone()) ) ),
&Token::ParClose => move_till_match_paren( out_stack, op_stack ) Token::ParClose => move_till_match_paren( out_stack, op_stack )
}; };
maybe_dump_shunting_yard_step( token_idx, token, out_stack, op_stack, &result ); maybe_dump_shunting_yard_step( token_idx, token, out_stack, op_stack, &result );
result result

View file

@ -52,14 +52,14 @@ impl Token {
} }
fn is_infix_plus( &self ) -> bool { fn is_infix_plus( &self ) -> bool {
match self { match *self {
&Token::InfixOp{ ref value, .. } => value == "+", Token::InfixOp{ ref value, .. } => value == "+",
_ => false _ => false
} }
} }
fn is_a_number( &self ) -> bool { fn is_a_number( &self ) -> bool {
match self { match *self {
&Token::Value{ ref value, .. } => Token::Value{ ref value, .. } =>
match value.parse::<i64>() { match value.parse::<i64>() {
Ok( _ ) => true, Ok( _ ) => true,
Err( _ ) => false Err( _ ) => false
@ -68,14 +68,14 @@ impl Token {
} }
} }
fn is_a_close_paren( &self ) -> bool { fn is_a_close_paren( &self ) -> bool {
match self { match *self {
&Token::ParClose => true, Token::ParClose => true,
_ => false, _ => false,
} }
} }
} }
pub fn strings_to_tokens( strings: &Vec<String> ) -> Result< Vec<(usize, Token)>, String > { pub fn strings_to_tokens( strings: &[String] ) -> Result< Vec<(usize, Token)>, String > {
let mut tokens_acc = Vec::with_capacity( strings.len() ); let mut tokens_acc = Vec::with_capacity( strings.len() );
let mut tok_idx = 1; let mut tok_idx = 1;
@ -122,7 +122,7 @@ pub fn strings_to_tokens( strings: &Vec<String> ) -> Result< Vec<(usize, Token)>
Ok( tokens_acc ) Ok( tokens_acc )
} }
fn maybe_dump_tokens_acc( tokens_acc: &Vec<(usize, Token)> ) { fn maybe_dump_tokens_acc( tokens_acc: &[(usize, Token)] ) {
use std::env; use std::env;
if let Ok(debug_var) = env::var( "EXPR_DEBUG_TOKENS" ) { if let Ok(debug_var) = env::var( "EXPR_DEBUG_TOKENS" ) {
@ -147,8 +147,9 @@ fn push_token_if_not_escaped( acc: &mut Vec<(usize, Token)>, tok_idx: usize, tok
let pre_prev = &acc[acc.len() - 2]; let pre_prev = &acc[acc.len() - 2];
! ( pre_prev.1.is_a_number() || pre_prev.1.is_a_close_paren() ) ! ( pre_prev.1.is_a_number() || pre_prev.1.is_a_close_paren() )
} }
else if prev_is_plus { true } else {
else { false }; prev_is_plus
};
if should_use_as_escaped { if should_use_as_escaped {
acc.pop(); acc.pop();

View file

@ -145,7 +145,7 @@ fn print_factors(num: u64) {
table_division(num, &mut factors); table_division(num, &mut factors);
factors.sort(); factors.sort();
for fac in factors.iter() { for fac in &factors {
print!(" {}", fac); print!(" {}", fac);
} }
println!(""); println!("");
@ -193,7 +193,7 @@ read from standard input.", NAME, VERSION);
} }
} }
} else { } else {
for num_str in matches.free.iter() { for num_str in &matches.free {
print_factors_str(num_str); print_factors_str(num_str);
} }
} }

View file

@ -17,13 +17,11 @@ pub fn big_add(a: u64, b: u64, m: u64) -> u64 {
let msb_mod_m = msb_mod_m % m; let msb_mod_m = msb_mod_m % m;
let Wrapping(res) = Wrapping(a) + Wrapping(b); let Wrapping(res) = Wrapping(a) + Wrapping(b);
let res = if b <= MAX_U64 - a { if b <= MAX_U64 - a {
res res
} else { } else {
(res + msb_mod_m) % m (res + msb_mod_m) % m
}; }
res
} }
// computes (a + b) % m using the russian peasant algorithm // computes (a + b) % m using the russian peasant algorithm

View file

@ -189,7 +189,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
let mut files = matches.free; let mut files = matches.free;
if files.is_empty() { if files.is_empty() {
files.push("-".to_string()); files.push("-".to_owned());
} }
let mut ostream = BufWriter::new(stdout()); let mut ostream = BufWriter::new(stdout());

View file

@ -24,7 +24,6 @@ struct BreakArgs<'a> {
} }
impl<'a> BreakArgs<'a> { impl<'a> BreakArgs<'a> {
#[inline(always)]
fn compute_width<'b>(&self, winfo: &WordInfo<'b>, posn: usize, fresh: bool) -> usize { fn compute_width<'b>(&self, winfo: &WordInfo<'b>, posn: usize, fresh: bool) -> usize {
if fresh { if fresh {
0 0
@ -99,7 +98,6 @@ fn break_simple<'a, T: Iterator<Item=&'a WordInfo<'a>>>(iter: T, args: &mut Brea
silent_unwrap!(args.ostream.write_all("\n".as_bytes())); silent_unwrap!(args.ostream.write_all("\n".as_bytes()));
} }
#[inline(always)]
fn accum_words_simple<'a>(args: &mut BreakArgs<'a>, (l, prev_punct): (usize, bool), winfo: &'a WordInfo<'a>) -> (usize, bool) { fn accum_words_simple<'a>(args: &mut BreakArgs<'a>, (l, prev_punct): (usize, bool), winfo: &'a WordInfo<'a>) -> (usize, bool) {
// compute the length of this word, considering how tabs will expand at this position on the line // compute the length of this word, considering how tabs will expand at this position on the line
let wlen = winfo.word_nchars + args.compute_width(winfo, l, false); let wlen = winfo.word_nchars + args.compute_width(winfo, l, false);
@ -310,8 +308,7 @@ fn find_kp_breakpoints<'a, T: Iterator<Item=&'a WordInfo<'a>>>(iter: T, args: &B
build_best_path(&linebreaks, active_breaks) build_best_path(&linebreaks, active_breaks)
} }
#[inline(always)] fn build_best_path<'a>(paths: &[LineBreak<'a>], active: &[usize]) -> Vec<(&'a WordInfo<'a>, bool)> {
fn build_best_path<'a>(paths: &Vec<LineBreak<'a>>, active: &Vec<usize>) -> Vec<(&'a WordInfo<'a>, bool)> {
let mut breakwords = vec!(); let mut breakwords = vec!();
// of the active paths, we select the one with the fewest demerits // of the active paths, we select the one with the fewest demerits
let mut best_idx = match active.iter().min_by_key(|&&a| paths[a].demerits) { let mut best_idx = match active.iter().min_by_key(|&&a| paths[a].demerits) {
@ -322,7 +319,7 @@ fn build_best_path<'a>(paths: &Vec<LineBreak<'a>>, active: &Vec<usize>) -> Vec<(
// now, chase the pointers back through the break list, recording // now, chase the pointers back through the break list, recording
// the words at which we should break // the words at which we should break
loop { loop {
let ref next_best = paths[best_idx]; let next_best = &paths[best_idx];
match next_best.linebreak { match next_best.linebreak {
None => return breakwords, None => return breakwords,
Some(prev) => { Some(prev) => {
@ -343,7 +340,6 @@ const DR_MULT: f32 = 600.0;
// DL_MULT is penalty multiplier for short words at end of line // DL_MULT is penalty multiplier for short words at end of line
const DL_MULT: f32 = 300.0; const DL_MULT: f32 = 300.0;
#[inline(always)]
fn compute_demerits(delta_len: isize, stretch: isize, wlen: isize, prev_rat: f32) -> (i64, f32) { fn compute_demerits(delta_len: isize, stretch: isize, wlen: isize, prev_rat: f32) -> (i64, f32) {
// how much stretch are we using? // how much stretch are we using?
let ratio = let ratio =
@ -377,7 +373,6 @@ fn compute_demerits(delta_len: isize, stretch: isize, wlen: isize, prev_rat: f32
(demerits, ratio) (demerits, ratio)
} }
#[inline(always)]
fn restart_active_breaks<'a>(args: &BreakArgs<'a>, active: &LineBreak<'a>, act_idx: usize, w: &'a WordInfo<'a>, slen: usize, min: usize) -> LineBreak<'a> { fn restart_active_breaks<'a>(args: &BreakArgs<'a>, active: &LineBreak<'a>, act_idx: usize, w: &'a WordInfo<'a>, slen: usize, min: usize) -> LineBreak<'a> {
let (break_before, line_length) = let (break_before, line_length) =
if active.fresh { if active.fresh {
@ -409,7 +404,6 @@ fn restart_active_breaks<'a>(args: &BreakArgs<'a>, active: &LineBreak<'a>, act_i
} }
// Number of spaces to add before a word, based on mode, newline, sentence start. // Number of spaces to add before a word, based on mode, newline, sentence start.
#[inline(always)]
fn compute_slen(uniform: bool, newline: bool, start: bool, punct: bool) -> usize { fn compute_slen(uniform: bool, newline: bool, start: bool, punct: bool) -> usize {
if uniform || newline { if uniform || newline {
if start || (newline && punct) { if start || (newline && punct) {
@ -424,8 +418,7 @@ fn compute_slen(uniform: bool, newline: bool, start: bool, punct: bool) -> usize
// If we're on a fresh line, slen=0 and we slice off leading whitespace. // If we're on a fresh line, slen=0 and we slice off leading whitespace.
// Otherwise, compute slen and leave whitespace alone. // Otherwise, compute slen and leave whitespace alone.
#[inline(always)] fn slice_if_fresh(fresh: bool, word: &str, start: usize, uniform: bool, newline: bool, sstart: bool, punct: bool) -> (usize, &str) {
fn slice_if_fresh<'a>(fresh: bool, word: &'a str, start: usize, uniform: bool, newline: bool, sstart: bool, punct: bool) -> (usize, &'a str) {
if fresh { if fresh {
(0, &word[start..]) (0, &word[start..])
} else { } else {
@ -434,14 +427,12 @@ fn slice_if_fresh<'a>(fresh: bool, word: &'a str, start: usize, uniform: bool, n
} }
// Write a newline and add the indent. // Write a newline and add the indent.
#[inline(always)]
fn write_newline(indent: &str, ostream: &mut BufWriter<Stdout>) { fn write_newline(indent: &str, ostream: &mut BufWriter<Stdout>) {
silent_unwrap!(ostream.write_all("\n".as_bytes())); silent_unwrap!(ostream.write_all("\n".as_bytes()));
silent_unwrap!(ostream.write_all(indent.as_bytes())); silent_unwrap!(ostream.write_all(indent.as_bytes()));
} }
// Write the word, along with slen spaces. // Write the word, along with slen spaces.
#[inline(always)]
fn write_with_spaces(word: &str, slen: usize, ostream: &mut BufWriter<Stdout>) { fn write_with_spaces(word: &str, slen: usize, ostream: &mut BufWriter<Stdout>) {
if slen == 2 { if slen == 2 {
silent_unwrap!(ostream.write_all(" ".as_bytes())); silent_unwrap!(ostream.write_all(" ".as_bytes()));

View file

@ -15,7 +15,6 @@ use unicode_width::UnicodeWidthChar;
use FileOrStdReader; use FileOrStdReader;
use FmtOptions; use FmtOptions;
#[inline(always)]
fn char_width(c: char) -> usize { fn char_width(c: char) -> usize {
if (c as usize) < 0xA0 { if (c as usize) < 0xA0 {
// if it is ASCII, call it exactly 1 wide (including control chars) // if it is ASCII, call it exactly 1 wide (including control chars)
@ -103,7 +102,7 @@ impl<'a> FileLines<'a> {
// we do it this way rather than byte indexing to support unicode whitespace chars // we do it this way rather than byte indexing to support unicode whitespace chars
let mut i = 0; let mut i = 0;
while (i < line.len()) && line.char_at(i).is_whitespace() { while (i < line.len()) && line.char_at(i).is_whitespace() {
i = match line.char_range_at(i) { CharRange { ch: _ , next: nxi } => nxi }; i = match line.char_range_at(i) { CharRange { next: nxi, .. } => nxi };
if line[i..].starts_with(pfx) { if line[i..].starts_with(pfx) {
return (true, i); return (true, i);
} }
@ -157,7 +156,7 @@ impl<'a> Iterator for FileLines<'a> {
// Err(true) indicates that this was a linebreak, // Err(true) indicates that this was a linebreak,
// which is important to know when detecting mail headers // which is important to know when detecting mail headers
if n.chars().all(|c| c.is_whitespace()) { if n.chars().all(|c| c.is_whitespace()) {
return Some(Line::NoFormatLine("\n".to_string(), true)); return Some(Line::NoFormatLine("\n".to_owned(), true));
} }
// if this line does not match the prefix, // if this line does not match the prefix,
@ -246,10 +245,10 @@ impl<'a> ParagraphStream<'a> {
// header field must be nonzero length // header field must be nonzero length
if colon_posn == 0 { return false; } if colon_posn == 0 { return false; }
return l_slice[..colon_posn].chars().all(|x| match x as usize { l_slice[..colon_posn].chars().all(|x| match x as usize {
y if y < 33 || y > 126 => false, y if y < 33 || y > 126 => false,
_ => true _ => true
}); })
} }
} }
} }
@ -263,9 +262,9 @@ impl<'a> Iterator for ParagraphStream<'a> {
let noformat = let noformat =
match self.lines.peek() { match self.lines.peek() {
None => return None, None => return None,
Some(l) => match l { Some(l) => match *l {
&Line::FormatLine(_) => false, Line::FormatLine(_) => false,
&Line::NoFormatLine(_, _) => true Line::NoFormatLine(_, _) => true
} }
}; };
@ -296,14 +295,14 @@ impl<'a> Iterator for ParagraphStream<'a> {
match self.lines.peek() { match self.lines.peek() {
None => break, None => break,
Some(l) => { Some(l) => {
match l { match *l {
&Line::FormatLine(ref x) => x, Line::FormatLine(ref x) => x,
&Line::NoFormatLine(..) => break Line::NoFormatLine(..) => break
} }
} }
}; };
if p_lines.len() == 0 { if p_lines.is_empty() {
// first time through the loop, get things set up // first time through the loop, get things set up
// detect mail header // detect mail header
if self.opts.mail && self.next_mail && ParagraphStream::is_mail_header(fl) { if self.opts.mail && self.next_mail && ParagraphStream::is_mail_header(fl) {
@ -410,7 +409,7 @@ impl<'a> ParaWords<'a> {
pw pw
} }
fn create_words<'r>(&'r mut self) { fn create_words(& mut self) {
if self.para.mail_header { if self.para.mail_header {
// no extra spacing for mail headers; always exactly 1 space // no extra spacing for mail headers; always exactly 1 space
// safe to trim_left on every line of a mail header, since the // safe to trim_left on every line of a mail header, since the
@ -445,7 +444,7 @@ impl<'a> ParaWords<'a> {
} }
} }
pub fn words(&'a self) -> Iter<'a, WordInfo<'a>> { return self.words.iter() } pub fn words(&'a self) -> Iter<'a, WordInfo<'a>> { self.words.iter() }
} }
struct WordSplit<'a> { struct WordSplit<'a> {
@ -546,7 +545,7 @@ impl<'a> Iterator for WordSplit<'a> {
// now record whether this word ends in punctuation // now record whether this word ends in punctuation
self.prev_punct = match self.string.char_range_at_reverse(self.position) { self.prev_punct = match self.string.char_range_at_reverse(self.position) {
CharRange { ch, next: _ } => WordSplit::is_punctuation(ch) CharRange { ch, .. } => WordSplit::is_punctuation(ch)
}; };
let (word, word_start_relative, before_tab, after_tab) = let (word, word_start_relative, before_tab, after_tab) =

View file

@ -53,10 +53,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
if matches.opt_present("w") { if matches.opt_present("w") {
matches.opt_str("w") matches.opt_str("w")
} else { } else {
match obs_width { obs_width
Some(v) => Some(v.to_string()),
None => None,
}
}; };
let width = match poss_width { let width = match poss_width {
Some(inp_width) => match inp_width.parse::<usize>() { Some(inp_width) => match inp_width.parse::<usize>() {
@ -66,7 +63,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
None => 80 None => 80
}; };
let files = if matches.free.is_empty() { let files = if matches.free.is_empty() {
vec!("-".to_string()) vec!("-".to_owned())
} else { } else {
matches.free matches.free
}; };
@ -82,7 +79,7 @@ fn handle_obsolete(args: &[String]) -> (Vec<String>, Option<String>) {
if slice.chars().next().unwrap() == '-' && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) { if slice.chars().next().unwrap() == '-' && slice.len() > 1 && slice.chars().nth(1).unwrap().is_digit(10) {
let mut v = args.to_vec(); let mut v = args.to_vec();
v.remove(i); v.remove(i);
return (v, Some(slice[1..].to_string())); return (v, Some(slice[1..].to_owned()));
} }
} }
(args.to_vec(), None) (args.to_vec(), None)
@ -90,7 +87,7 @@ fn handle_obsolete(args: &[String]) -> (Vec<String>, Option<String>) {
#[inline] #[inline]
fn fold(filenames: Vec<String>, bytes: bool, spaces: bool, width: usize) { fn fold(filenames: Vec<String>, bytes: bool, spaces: bool, width: usize) {
for filename in filenames.iter() { for filename in &filenames {
let filename: &str = &filename; let filename: &str = &filename;
let mut stdin_buf; let mut stdin_buf;
let mut file_buf; let mut file_buf;
@ -168,7 +165,7 @@ fn fold_file<T: Read>(mut file: BufReader<T>, bytes: bool, spaces: bool, width:
(slice, "", 0) (slice, "", 0)
}; };
println!("{}", out); println!("{}", out);
(val.to_string(), ncount) (val.to_owned(), ncount)
}; };
output = val; output = val;
count = ncount; count = ncount;

View file

@ -124,7 +124,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
let strict = matches.opt_present("strict"); let strict = matches.opt_present("strict");
let warn = matches.opt_present("warn") && !status; let warn = matches.opt_present("warn") && !status;
let files = if matches.free.is_empty() { let files = if matches.free.is_empty() {
vec!("-".to_string()) vec!("-".to_owned())
} else { } else {
matches.free matches.free
}; };
@ -158,7 +158,7 @@ Compute and check message digests.", NAME, VERSION, spec);
pipe_print!("{}", opts.usage(&msg)); pipe_print!("{}", opts.usage(&msg));
} }
fn hashsum<'a>(algoname: &str, mut digest: Box<Digest+'a>, files: Vec<String>, binary: bool, check: bool, tag: bool, status: bool, quiet: bool, strict: bool, warn: bool) -> Result<(), i32> { fn hashsum(algoname: &str, mut digest: Box<Digest>, files: Vec<String>, binary: bool, check: bool, tag: bool, status: bool, quiet: bool, strict: bool, warn: bool) -> Result<(), i32> {
let mut bad_format = 0; let mut bad_format = 0;
let mut failed = 0; let mut failed = 0;
let binary_marker = if binary { let binary_marker = if binary {
@ -166,7 +166,7 @@ fn hashsum<'a>(algoname: &str, mut digest: Box<Digest+'a>, files: Vec<String>, b
} else { } else {
" " " "
}; };
for filename in files.iter() { for filename in &files {
let filename: &str = filename; let filename: &str = filename;
let stdin_buf; let stdin_buf;
let file_buf; let file_buf;

View file

@ -130,7 +130,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
} else { } else {
let mut firstime = true; let mut firstime = true;
for file in files.iter() { for file in &files {
if settings.verbose { if settings.verbose {
if !firstime { pipe_println!(""); } if !firstime { pipe_println!(""); }
pipe_println!("==> {} <==", file); pipe_println!("==> {} <==", file);

View file

@ -82,7 +82,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
if !hashset.contains(&addr) { if !hashset.contains(&addr) {
let mut ip = format!("{}", addr); let mut ip = format!("{}", addr);
if ip.ends_with(":1") { if ip.ends_with(":1") {
ip = ip[..ip.len()-2].to_string(); ip = ip[..ip.len()-2].to_owned();
} }
output.push_str(&ip); output.push_str(&ip);
output.push_str(" "); output.push_str(" ");
@ -153,7 +153,7 @@ fn xgethostname() -> String {
let last_char = name.iter().position(|byte| *byte == 0).unwrap_or(namelen); let last_char = name.iter().position(|byte| *byte == 0).unwrap_or(namelen);
str::from_utf8(&name[..last_char]).unwrap().to_string() str::from_utf8(&name[..last_char]).unwrap().to_owned()
} }
#[cfg(any(target_os = "macos", target_os = "freebsd"))] #[cfg(any(target_os = "macos", target_os = "freebsd"))]

View file

@ -196,7 +196,7 @@ fn pretty(possible_pw: Option<c_passwd>) {
let pw = unsafe { getpwuid(rid) }; let pw = unsafe { getpwuid(rid) };
let is_same_user = unsafe { let is_same_user = unsafe {
String::from_utf8_lossy(CStr::from_ptr(read(pw).pw_name).to_bytes()).to_string() == login String::from_utf8_lossy(CStr::from_ptr(read(pw).pw_name).to_bytes()) == login
}; };
if pw.is_null() || is_same_user { if pw.is_null() || is_same_user {
@ -374,11 +374,11 @@ fn id_print(possible_pw: Option<c_passwd>, p_euid: bool, p_egid: bool) {
} }
} }
if groups.len() > 0 { if !groups.is_empty() {
print!(" groups="); print!(" groups=");
let mut first = true; let mut first = true;
for &gr in groups.iter() { for &gr in &groups {
if !first { print!(",") } if !first { print!(",") }
print!("{}", gr); print!("{}", gr);
let group = unsafe { getgrgid(gr) }; let group = unsafe { getgrgid(gr) };

View file

@ -66,7 +66,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
}; };
match mode { match mode {
Mode::Kill => return kill(&matches.opt_str("signal").unwrap_or(obs_signal.unwrap_or("9".to_string())), matches.free), Mode::Kill => return kill(&matches.opt_str("signal").unwrap_or(obs_signal.unwrap_or("9".to_owned())), matches.free),
Mode::Table => table(), Mode::Table => table(),
Mode::List => list(matches.opt_str("list")), Mode::List => list(matches.opt_str("list")),
Mode::Help => help(&opts), Mode::Help => help(&opts),
@ -91,7 +91,7 @@ fn handle_obsolete(mut args: Vec<String>) -> (Vec<String>, Option<String>) {
Ok(num) => { Ok(num) => {
if uucore::signals::is_signal(num) { if uucore::signals::is_signal(num) {
args.remove(i); args.remove(i);
return (args, Some(val.to_string())); return (args, Some(val.to_owned()));
} }
} }
Err(_)=> break /* getopts will error out for us */ Err(_)=> break /* getopts will error out for us */
@ -105,7 +105,7 @@ fn handle_obsolete(mut args: Vec<String>) -> (Vec<String>, Option<String>) {
fn table() { fn table() {
let mut name_width = 0; let mut name_width = 0;
/* Compute the maximum width of a signal name. */ /* Compute the maximum width of a signal name. */
for s in ALL_SIGNALS.iter() { for s in &ALL_SIGNALS {
if s.name.len() > name_width { if s.name.len() > name_width {
name_width = s.name.len() name_width = s.name.len()
} }
@ -122,7 +122,7 @@ fn table() {
} }
fn print_signal(signal_name_or_value: &str) { fn print_signal(signal_name_or_value: &str) {
for signal in ALL_SIGNALS.iter() { for signal in &ALL_SIGNALS {
if signal.name == signal_name_or_value || (format!("SIG{}", signal.name)) == signal_name_or_value { if signal.name == signal_name_or_value || (format!("SIG{}", signal.name)) == signal_name_or_value {
println!("{}", signal.value); println!("{}", signal.value);
exit!(EXIT_OK as i32) exit!(EXIT_OK as i32)
@ -172,7 +172,7 @@ fn kill(signalname: &str, pids: std::vec::Vec<String>) -> i32 {
Some(x) => x, Some(x) => x,
None => crash!(EXIT_ERR, "unknown signal name {}", signalname) None => crash!(EXIT_ERR, "unknown signal name {}", signalname)
}; };
for pid in pids.iter() { for pid in &pids {
match pid.parse::<usize>() { match pid.parse::<usize>() {
Ok(x) => { Ok(x) => {
if unsafe { libc::kill(x as pid_t, signal_value as c_int) } != 0 { if unsafe { libc::kill(x as pid_t, signal_value as c_int) } != 0 {

View file

@ -112,7 +112,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
} }
} }
} else { } else {
"~".to_string() "~".to_owned()
}; };
if matches.opt_present("T") && matches.opt_present("t") { if matches.opt_present("T") && matches.opt_present("t") {
@ -216,13 +216,10 @@ fn link_files_in_dir(files: &[PathBuf], target_dir: &PathBuf, settings: &Setting
} }
}; };
match link(srcpath, &targetpath, settings) { if let Err(e) = link(srcpath, &targetpath, settings) {
Err(e) => { show_error!("cannot link '{}' to '{}': {}",
show_error!("cannot link '{}' to '{}': {}", targetpath.display(), srcpath.display(), e);
targetpath.display(), srcpath.display(), e); all_successful = false;
all_successful = false;
},
_ => {}
} }
} }
if all_successful { 0 } else { 1 } if all_successful { 0 } else { 1 }
@ -231,10 +228,8 @@ fn link_files_in_dir(files: &[PathBuf], target_dir: &PathBuf, settings: &Setting
fn link(src: &PathBuf, dst: &PathBuf, settings: &Settings) -> Result<()> { fn link(src: &PathBuf, dst: &PathBuf, settings: &Settings) -> Result<()> {
let mut backup_path = None; let mut backup_path = None;
if dst.is_dir() { if dst.is_dir() && settings.no_target_dir {
if settings.no_target_dir { try!(fs::remove_dir(dst));
try!(fs::remove_dir(dst));
}
} }
if is_symlink(dst) || dst.exists() { if is_symlink(dst) || dst.exists() {
@ -290,8 +285,8 @@ fn read_yes() -> bool {
} }
} }
fn simple_backup_path(path: &PathBuf, suffix: &String) -> PathBuf { fn simple_backup_path(path: &PathBuf, suffix: &str) -> PathBuf {
let mut p = path.as_os_str().to_str().unwrap().to_string(); let mut p = path.as_os_str().to_str().unwrap().to_owned();
p.push_str(suffix); p.push_str(suffix);
PathBuf::from(p) PathBuf::from(p)
} }
@ -307,8 +302,8 @@ fn numbered_backup_path(path: &PathBuf) -> PathBuf {
} }
} }
fn existing_backup_path(path: &PathBuf, suffix: &String) -> PathBuf { fn existing_backup_path(path: &PathBuf, suffix: &str) -> PathBuf {
let test_path = simple_backup_path(path, &".~1~".to_string()); let test_path = simple_backup_path(path, &".~1~".to_owned());
if test_path.exists() { if test_path.exists() {
return numbered_backup_path(path); return numbered_backup_path(path);
} }

View file

@ -55,17 +55,17 @@ pub fn uumain(args: Vec<String>) -> i32 {
// Translate a ~str in octal form to u16, default to 755 // Translate a ~str in octal form to u16, default to 755
// Not tested on Windows // Not tested on Windows
let mode_match = matches.opts_str(&["mode".to_string()]); let mode_match = matches.opts_str(&["mode".to_owned()]);
let mode: u16 = if mode_match.is_some() { let mode: u16 = if mode_match.is_some() {
let m = mode_match.unwrap(); let m = mode_match.unwrap();
let res: Option<u16> = u16::from_str_radix(&m, 8).ok(); let res: Option<u16> = u16::from_str_radix(&m, 8).ok();
if res.is_some() { if res.is_some() {
unsafe { std::mem::transmute(res.unwrap()) } res.unwrap()
} else { } else {
crash!(1, "no mode given"); crash!(1, "no mode given");
} }
} else { } else {
unsafe { std::mem::transmute(0o755 as u16) } 0o755 as u16
}; };
let dirs = matches.free; let dirs = matches.free;
@ -88,7 +88,7 @@ fn print_help(opts: &getopts::Options) {
fn exec(dirs: Vec<String>, recursive: bool, mode: u16, verbose: bool) -> i32 { fn exec(dirs: Vec<String>, recursive: bool, mode: u16, verbose: bool) -> i32 {
let mut status = 0; let mut status = 0;
let empty = Path::new(""); let empty = Path::new("");
for dir in dirs.iter() { for dir in &dirs {
let path = Path::new(dir); let path = Path::new(dir);
if recursive { if recursive {
let mut pathbuf = PathBuf::new(); let mut pathbuf = PathBuf::new();

View file

@ -66,7 +66,7 @@ Create a FIFO with the given name.", NAME, VERSION);
}; };
let mut exit_status = 0; let mut exit_status = 0;
for f in matches.free.iter() { for f in &matches.free {
let err = unsafe { mkfifo(CString::new(f.as_bytes()).unwrap().as_ptr(), mode as libc::mode_t) }; let err = unsafe { mkfifo(CString::new(f.as_bytes()).unwrap().as_ptr(), mode as libc::mode_t) };
if err == -1 { if err == -1 {
show_error!("creating '{}': {}", f, Error::last_os_error().raw_os_error().unwrap()); show_error!("creating '{}': {}", f, Error::last_os_error().raw_os_error().unwrap());

View file

@ -88,16 +88,16 @@ pub fn uumain(args: Vec<String>) -> i32 {
} else { } else {
crash!(1, "Template should end with 'X' when you specify suffix option.") crash!(1, "Template should end with 'X' when you specify suffix option.")
}, },
None => (p, r, s.to_string()) None => (p, r, s.to_owned())
}, },
None => ("",0, "".to_string()) None => ("",0, "".to_owned())
}; };
if rand < 3 { if rand < 3 {
crash!(1, "Too few 'X's in template") crash!(1, "Too few 'X's in template")
} }
if suffix.chars().any(|c| is_separator(c)) { if suffix.chars().any(is_separator) {
crash!(1, "suffix cannot contain any path separators"); crash!(1, "suffix cannot contain any path separators");
} }
@ -168,7 +168,7 @@ pub fn dry_exec(mut tmpdir: PathBuf, prefix: &str, rand: usize, suffix: &str) ->
} }
tmpdir.push(String::from(buf)); tmpdir.push(String::from(buf));
println!("{}", tmpdir.display()); println!("{}", tmpdir.display());
return 0; 0
} }
@ -203,5 +203,5 @@ fn exec(tmpdir: PathBuf, prefix: &str, rand: usize, suffix: &str, make_dir: bool
// I call a dengeros function `forget`. // I call a dengeros function `forget`.
forget(tmpfile); forget(tmpfile);
return 0; 0
} }

View file

@ -128,7 +128,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
} }
} }
} else { } else {
"~".to_string() "~".to_owned()
}; };
if matches.opt_present("T") && matches.opt_present("t") { if matches.opt_present("T") && matches.opt_present("t") {
@ -192,8 +192,8 @@ fn exec(files: &[PathBuf], b: Behaviour) -> i32 {
return 1; return 1;
}, },
2 => { 2 => {
let ref source = files[0]; let source = &files[0];
let ref target = files[1]; let target = &files[1];
if !source.exists() { if !source.exists() {
show_error!("cannot stat {}: No such file or directory", source.display()); show_error!("cannot stat {}: No such file or directory", source.display());
return 1; return 1;
@ -219,12 +219,9 @@ fn exec(files: &[PathBuf], b: Behaviour) -> i32 {
return move_files_into_dir(&[source.clone()], target, &b); return move_files_into_dir(&[source.clone()], target, &b);
} }
match rename(source, target, &b) { if let Err(e) = rename(source, target, &b) {
Err(e) => { show_error!("{}", e);
show_error!("{}", e); return 1;
return 1;
},
_ => {}
} }
} }
_ => { _ => {
@ -259,13 +256,10 @@ fn move_files_into_dir(files: &[PathBuf], target_dir: &PathBuf, b: &Behaviour) -
} }
}; };
match rename(sourcepath, &targetpath, b) { if let Err(e) = rename(sourcepath, &targetpath, b) {
Err(e) => { show_error!("mv: cannot move {} to {}: {}",
show_error!("mv: cannot move {} to {}: {}", sourcepath.display(), targetpath.display(), e);
sourcepath.display(), targetpath.display(), e); all_successful = false;
all_successful = false;
},
_ => {}
} }
}; };
if all_successful { 0 } else { 1 } if all_successful { 0 } else { 1 }
@ -326,10 +320,10 @@ fn read_yes() -> bool {
} }
} }
fn simple_backup_path(path: &PathBuf, suffix: &String) -> PathBuf { fn simple_backup_path(path: &PathBuf, suffix: &str) -> PathBuf {
let mut p = path.as_os_str().to_str().unwrap().to_string(); let mut p = path.as_os_str().to_str().unwrap().to_owned();
p.push_str(suffix); p.push_str(suffix);
return PathBuf::from(p); PathBuf::from(p)
} }
fn numbered_backup_path(path: &PathBuf) -> PathBuf { fn numbered_backup_path(path: &PathBuf) -> PathBuf {
@ -343,8 +337,8 @@ fn numbered_backup_path(path: &PathBuf) -> PathBuf {
} }
} }
fn existing_backup_path(path: &PathBuf, suffix: &String) -> PathBuf { fn existing_backup_path(path: &PathBuf, suffix: &str) -> PathBuf {
let test_path = simple_backup_path(path, &".~1~".to_string()); let test_path = simple_backup_path(path, &".~1~".to_owned());
if test_path.exists() { if test_path.exists() {
return numbered_backup_path(path); return numbered_backup_path(path);
} }

View file

@ -73,7 +73,7 @@ process).", NAME, VERSION);
let adjustment = match matches.opt_str("adjustment") { let adjustment = match matches.opt_str("adjustment") {
Some(nstr) => { Some(nstr) => {
if matches.free.len() == 0 { if matches.free.is_empty() {
show_error!("A command must be given with an adjustment. show_error!("A command must be given with an adjustment.
Try \"{} --help\" for more information.", args[0]); Try \"{} --help\" for more information.", args[0]);
return 125; return 125;
@ -87,7 +87,7 @@ process).", NAME, VERSION);
} }
}, },
None => { None => {
if matches.free.len() == 0 { if matches.free.is_empty() {
println!("{}", niceness); println!("{}", niceness);
return 0; return 0;
} }

View file

@ -10,7 +10,7 @@ fn parse_style(chars: &[char]) -> Result<::NumberingStyle, String> {
} else if chars.len() == 1 && chars[0] == 'n' { } else if chars.len() == 1 && chars[0] == 'n' {
Ok(::NumberingStyle::NumberForNone) Ok(::NumberingStyle::NumberForNone)
} else if chars.len() > 1 && chars[0] == 'p' { } else if chars.len() > 1 && chars[0] == 'p' {
let s: String = chars[1..].iter().map(|c| *c).collect(); let s: String = chars[1..].iter().cloned().collect();
match regex::Regex::new(&s) { match regex::Regex::new(&s) {
Ok(re) => Ok(::NumberingStyle::NumberForRegularExpression(re)), Ok(re) => Ok(::NumberingStyle::NumberForRegularExpression(re)),
Err(_) => Err(String::from("Illegal regular expression")), Err(_) => Err(String::from("Illegal regular expression")),

View file

@ -124,9 +124,9 @@ pub fn uumain(args: Vec<String>) -> i32 {
// Update the settings from the command line options, and terminate the // Update the settings from the command line options, and terminate the
// program if some options could not successfully be parsed. // program if some options could not successfully be parsed.
let parse_errors = helper::parse_options(&mut settings, &given_options); let parse_errors = helper::parse_options(&mut settings, &given_options);
if parse_errors.len() > 0 { if !parse_errors.is_empty() {
show_error!("Invalid arguments supplied."); show_error!("Invalid arguments supplied.");
for message in parse_errors.iter() { for message in &parse_errors {
println!("{}", message); println!("{}", message);
} }
return 1; return 1;
@ -135,7 +135,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
let files = given_options.free; let files = given_options.free;
let mut read_stdin = files.is_empty(); let mut read_stdin = files.is_empty();
for file in files.iter() { for file in &files {
if file == "-" { if file == "-" {
// If both file names and '-' are specified, we choose to treat first all // If both file names and '-' are specified, we choose to treat first all
// regular files, and then read from stdin last. // regular files, and then read from stdin last.
@ -179,7 +179,7 @@ fn nl<T: Read> (reader: &mut BufReader<T>, settings: &Settings) {
let mut line_filter : fn(&str, &regex::Regex) -> bool = pass_regex; let mut line_filter : fn(&str, &regex::Regex) -> bool = pass_regex;
for mut l in reader.lines().map(|r| r.unwrap()) { for mut l in reader.lines().map(|r| r.unwrap()) {
// Sanitize the string. We want to print the newline ourselves. // Sanitize the string. We want to print the newline ourselves.
if l.len() > 0 && l.chars().rev().next().unwrap() == '\n' { if !l.is_empty() && l.chars().rev().next().unwrap() == '\n' {
l.pop(); l.pop();
} }
// Next we iterate through the individual chars to see if this // Next we iterate through the individual chars to see if this

View file

@ -54,7 +54,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
if matches.opt_present("V") { println!("{} {}", NAME, VERSION); return 0 } if matches.opt_present("V") { println!("{} {}", NAME, VERSION); return 0 }
if matches.opt_present("h") { show_usage(&opts); return 0 } if matches.opt_present("h") { show_usage(&opts); return 0 }
if matches.free.len() == 0 { if matches.free.is_empty() {
show_error!("Missing operand: COMMAND"); show_error!("Missing operand: COMMAND");
println!("Try `{} --help` for more information.", NAME); println!("Try `{} --help` for more information.", NAME);
return 1 return 1

View file

@ -49,7 +49,7 @@ FILE, separated by TABs, to standard output.", NAME, VERSION);
println!("{} {}", NAME, VERSION); println!("{} {}", NAME, VERSION);
} else { } else {
let serial = matches.opt_present("serial"); let serial = matches.opt_present("serial");
let delimiters = matches.opt_str("delimiters").unwrap_or("\t".to_string()); let delimiters = matches.opt_str("delimiters").unwrap_or("\t".to_owned());
paste(matches.free, serial, delimiters); paste(matches.free, serial, delimiters);
} }
@ -72,7 +72,7 @@ fn paste(filenames: Vec<String>, serial: bool, delimiters: String) {
let mut delim_count = 0; let mut delim_count = 0;
if serial { if serial {
for file in files.iter_mut() { for file in &mut files {
let mut output = String::new(); let mut output = String::new();
loop { loop {
let mut line = String::new(); let mut line = String::new();

View file

@ -66,12 +66,9 @@ pub fn exec(args: Vec<String>, separator: &str) {
return; return;
} }
for env_var in args.iter() { for env_var in &args {
match env::var(env_var) { if let Ok(var) = env::var(env_var) {
Ok(var) => { print!("{}{}", var, separator);
print!("{}{}", var, separator);
}
_ => ()
} }
} }
} }

View file

@ -60,9 +60,9 @@ impl Default for Config {
input_ref : false, input_ref : false,
right_ref : false, right_ref : false,
ignore_case : false, ignore_case : false,
macro_name : "xx".to_string(), macro_name : "xx".to_owned(),
trunc_str : "/".to_string(), trunc_str : "/".to_owned(),
context_regex : "\\w+".to_string(), context_regex : "\\w+".to_owned(),
line_width : 72, line_width : 72,
gap_size : 3 gap_size : 3
} }
@ -109,9 +109,9 @@ impl WordFilter {
if matches.opt_present("W") { if matches.opt_present("W") {
matches.opt_str("W").expect("parsing options failed!") matches.opt_str("W").expect("parsing options failed!")
} else if config.gnu_ext { } else if config.gnu_ext {
"\\w+".to_string() "\\w+".to_owned()
} else { } else {
"[^ \t\n]+".to_string() "[^ \t\n]+".to_owned()
}; };
WordFilter { WordFilter {
only_specified: o, only_specified: o,
@ -153,7 +153,7 @@ fn get_config(matches: &Matches) -> Config {
if matches.opt_present("G") { if matches.opt_present("G") {
config.gnu_ext = false; config.gnu_ext = false;
config.format = OutFormat::Roff; config.format = OutFormat::Roff;
config.context_regex = "[^ \t\n]+".to_string(); config.context_regex = "[^ \t\n]+".to_owned();
} else { } else {
crash!(1, "GNU extensions not implemented yet"); crash!(1, "GNU extensions not implemented yet");
} }
@ -166,11 +166,11 @@ fn get_config(matches: &Matches) -> Config {
config.ignore_case = matches.opt_present("f"); config.ignore_case = matches.opt_present("f");
if matches.opt_present("M") { if matches.opt_present("M") {
config.macro_name = config.macro_name =
matches.opt_str("M").expect(err_msg).to_string(); matches.opt_str("M").expect(err_msg);
} }
if matches.opt_present("F") { if matches.opt_present("F") {
config.trunc_str = config.trunc_str =
matches.opt_str("F").expect(err_msg).to_string(); matches.opt_str("F").expect(err_msg);
} }
if matches.opt_present("w") { if matches.opt_present("w") {
let width_str = matches.opt_str("w").expect(err_msg); let width_str = matches.opt_str("w").expect(err_msg);
@ -191,7 +191,7 @@ fn get_config(matches: &Matches) -> Config {
config config
} }
fn read_input(input_files: &Vec<String>, config: &Config) -> fn read_input(input_files: &[String], config: &Config) ->
HashMap<String, (Vec<String>, usize)> { HashMap<String, (Vec<String>, usize)> {
let mut file_map : HashMap<String, (Vec<String>, usize)> = let mut file_map : HashMap<String, (Vec<String>, usize)> =
HashMap::new(); HashMap::new();
@ -219,7 +219,7 @@ fn read_input(input_files: &Vec<String>, config: &Config) ->
let lines: Vec<String> = reader.lines().map(|x| crash_if_err!(1, x)) let lines: Vec<String> = reader.lines().map(|x| crash_if_err!(1, x))
.collect(); .collect();
let size = lines.len(); let size = lines.len();
file_map.insert(filename.to_string(), (lines, lines_so_far)); file_map.insert(filename.to_owned(), (lines, lines_so_far));
lines_so_far += size lines_so_far += size
} }
file_map file_map
@ -234,7 +234,7 @@ fn create_word_set(config: &Config, filter: &WordFilter,
for (file, lines) in file_map.iter() { for (file, lines) in file_map.iter() {
let mut count: usize = 0; let mut count: usize = 0;
let offs = lines.1; let offs = lines.1;
for line in (lines.0).iter() { for line in &lines.0 {
// if -r, exclude reference from word set // if -r, exclude reference from word set
let (ref_beg, ref_end) = match ref_reg.find(line) { let (ref_beg, ref_end) = match ref_reg.find(line) {
Some(x) => x, Some(x) => x,
@ -245,7 +245,7 @@ fn create_word_set(config: &Config, filter: &WordFilter,
if config.input_ref && ((beg, end) == (ref_beg, ref_end)) { if config.input_ref && ((beg, end) == (ref_beg, ref_end)) {
continue; continue;
} }
let mut word = line[beg .. end].to_string(); let mut word = line[beg .. end].to_owned();
if filter.only_specified && if filter.only_specified &&
!(filter.only_set.contains(&word)) { !(filter.only_set.contains(&word)) {
continue; continue;
@ -272,7 +272,7 @@ fn create_word_set(config: &Config, filter: &WordFilter,
word_set word_set
} }
fn get_reference(config: &Config, word_ref: &WordRef, line: &String) -> fn get_reference(config: &Config, word_ref: &WordRef, line: &str) ->
String { String {
if config.auto_ref { if config.auto_ref {
format!("{}:{}", word_ref.filename, word_ref.local_line_nr + 1) format!("{}:{}", word_ref.filename, word_ref.local_line_nr + 1)
@ -288,12 +288,12 @@ fn get_reference(config: &Config, word_ref: &WordRef, line: &String) ->
} }
} }
fn assert_str_integrity(s: &Vec<char>, beg: usize, end: usize) { fn assert_str_integrity(s: &[char], beg: usize, end: usize) {
assert!(beg <= end); assert!(beg <= end);
assert!(end <= s.len()); assert!(end <= s.len());
} }
fn trim_broken_word_left(s: &Vec<char>, beg: usize, end: usize) -> usize { fn trim_broken_word_left(s: &[char], beg: usize, end: usize) -> usize {
assert_str_integrity(s, beg, end); assert_str_integrity(s, beg, end);
if beg == end || beg == 0 || s[beg].is_whitespace() || if beg == end || beg == 0 || s[beg].is_whitespace() ||
s[beg-1].is_whitespace() { s[beg-1].is_whitespace() {
@ -306,7 +306,7 @@ fn trim_broken_word_left(s: &Vec<char>, beg: usize, end: usize) -> usize {
b b
} }
fn trim_broken_word_right(s: &Vec<char>, beg: usize, end: usize) -> usize { fn trim_broken_word_right(s: &[char], beg: usize, end: usize) -> usize {
assert_str_integrity(s, beg, end); assert_str_integrity(s, beg, end);
if beg == end || end == s.len() || s[end-1].is_whitespace() || if beg == end || end == s.len() || s[end-1].is_whitespace() ||
s[end].is_whitespace() { s[end].is_whitespace() {
@ -319,7 +319,7 @@ fn trim_broken_word_right(s: &Vec<char>, beg: usize, end: usize) -> usize {
e e
} }
fn trim_idx(s: &Vec<char>, beg: usize, end: usize) -> (usize, usize) { fn trim_idx(s: &[char], beg: usize, end: usize) -> (usize, usize) {
assert_str_integrity(s, beg, end); assert_str_integrity(s, beg, end);
let mut b = beg; let mut b = beg;
let mut e = end; let mut e = end;
@ -332,11 +332,11 @@ fn trim_idx(s: &Vec<char>, beg: usize, end: usize) -> (usize, usize) {
(b,e) (b,e)
} }
fn get_output_chunks(all_before: &String, keyword: &String, all_after: &String, fn get_output_chunks(all_before: &str, keyword: &str, all_after: &str,
config: &Config) -> (String, String, String, String) { config: &Config) -> (String, String, String, String) {
assert_eq!(all_before.trim().to_string(), *all_before); assert_eq!(all_before.trim().to_owned(), *all_before);
assert_eq!(keyword.trim().to_string(), *keyword); assert_eq!(keyword.trim().to_owned(), *keyword);
assert_eq!(all_after.trim().to_string(), *all_after); assert_eq!(all_after.trim().to_owned(), *all_after);
let mut head = String::new(); let mut head = String::new();
let mut before = String::new(); let mut before = String::new();
let mut after = String::new(); let mut after = String::new();
@ -398,7 +398,7 @@ fn get_output_chunks(all_before: &String, keyword: &String, all_after: &String,
} }
// add space before "after" if needed // add space before "after" if needed
if after.len() > 0 { if !after.is_empty() {
after = format!(" {}", after); after = format!(" {}", after);
} }
@ -407,7 +407,7 @@ fn get_output_chunks(all_before: &String, keyword: &String, all_after: &String,
fn tex_mapper(x: char) -> String { fn tex_mapper(x: char) -> String {
match x { match x {
'\\' => "\\backslash{}".to_string(), '\\' => "\\backslash{}".to_owned(),
'$' | '%' | '#' | '&' | '_' => format!("\\{}", x), '$' | '%' | '#' | '&' | '_' => format!("\\{}", x),
'}' | '{' => format!("$\\{}$", x), '}' | '{' => format!("$\\{}$", x),
_ => x.to_string() _ => x.to_string()
@ -416,14 +416,14 @@ fn tex_mapper(x: char) -> String {
fn adjust_tex_str(context: &str) -> String { fn adjust_tex_str(context: &str) -> String {
let ws_reg = Regex::new(r"[\t\n\v\f\r ]").unwrap(); let ws_reg = Regex::new(r"[\t\n\v\f\r ]").unwrap();
let mut fix: String = ws_reg.replace_all(context, " ").trim().to_string(); let mut fix: String = ws_reg.replace_all(context, " ").trim().to_owned();
let mapped_chunks: Vec<String> = fix.chars().map(tex_mapper).collect(); let mapped_chunks: Vec<String> = fix.chars().map(tex_mapper).collect();
fix = mapped_chunks.join(""); fix = mapped_chunks.join("");
fix fix
} }
fn format_tex_line(config: &Config, word_ref: &WordRef, line: &String, fn format_tex_line(config: &Config, word_ref: &WordRef, line: &str,
reference: &String) -> String { reference: &str) -> String {
let mut output = String::new(); let mut output = String::new();
output.push_str(&format!("\\{} ", config.macro_name)); output.push_str(&format!("\\{} ", config.macro_name));
let all_before = if config.input_ref { let all_before = if config.input_ref {
@ -449,7 +449,7 @@ fn format_tex_line(config: &Config, word_ref: &WordRef, line: &String,
fn adjust_roff_str(context: &str) -> String { fn adjust_roff_str(context: &str) -> String {
let ws_reg = Regex::new(r"[\t\n\v\f\r]").unwrap(); let ws_reg = Regex::new(r"[\t\n\v\f\r]").unwrap();
ws_reg.replace_all(context, " ").replace("\"", "\"\"").trim().to_string() ws_reg.replace_all(context, " ").replace("\"", "\"\"").trim().to_owned()
} }
fn format_roff_line(config: &Config, word_ref: &WordRef, line: &str, fn format_roff_line(config: &Config, word_ref: &WordRef, line: &str,
@ -478,7 +478,7 @@ fn format_roff_line(config: &Config, word_ref: &WordRef, line: &str,
fn write_traditional_output(config: &Config, fn write_traditional_output(config: &Config,
file_map: &HashMap<String, (Vec<String>,usize)>, file_map: &HashMap<String, (Vec<String>,usize)>,
words: &BTreeSet<WordRef>, output_filename: &String) { words: &BTreeSet<WordRef>, output_filename: &str) {
let mut writer: BufWriter<Box<Write>> = BufWriter::new( let mut writer: BufWriter<Box<Write>> = BufWriter::new(
if output_filename == "-" { if output_filename == "-" {
Box::new(stdout()) Box::new(stdout())
@ -555,7 +555,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
let output_file = if !config.gnu_ext && matches.free.len() == 2 { let output_file = if !config.gnu_ext && matches.free.len() == 2 {
matches.free[1].clone() matches.free[1].clone()
} else { } else {
"-".to_string() "-".to_owned()
}; };
write_traditional_output(&config, &file_map, &word_set, &output_file); write_traditional_output(&config, &file_map, &word_set, &output_file);
0 0

View file

@ -75,18 +75,16 @@ pub fn uumain(args: Vec<String>) -> i32 {
} }
let files = matches.free; let files = matches.free;
if files.len() == 0 { if files.is_empty() {
crash!(1, "missing operand\nTry {} --help for more information", NAME); crash!(1, "missing operand\nTry {} --help for more information", NAME);
} }
if no_newline && files.len() > 1 { if no_newline && files.len() > 1 && !silent {
if !silent { eprintln!("{}: ignoring --no-newline with multiple arguments", NAME);
eprintln!("{}: ignoring --no-newline with multiple arguments", NAME); no_newline = false;
no_newline = false;
}
} }
for f in files.iter() { for f in &files {
let p = PathBuf::from(f); let p = PathBuf::from(f);
if can_mode == CanonicalizeMode::None { if can_mode == CanonicalizeMode::None {
match fs::read_link(&p) { match fs::read_link(&p) {

View file

@ -44,7 +44,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
if matches.opt_present("V") { version(); return 0 } if matches.opt_present("V") { version(); return 0 }
if matches.opt_present("h") { show_usage(&opts); return 0 } if matches.opt_present("h") { show_usage(&opts); return 0 }
if matches.free.len() == 0 { if matches.free.is_empty() {
show_error!("Missing operand: FILENAME, at least one is required"); show_error!("Missing operand: FILENAME, at least one is required");
println!("Try `{} --help` for more information.", NAME); println!("Try `{} --help` for more information.", NAME);
return 1 return 1
@ -54,7 +54,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
let zero = matches.opt_present("z"); let zero = matches.opt_present("z");
let quiet = matches.opt_present("q"); let quiet = matches.opt_present("q");
let mut retcode = 0; let mut retcode = 0;
for path in matches.free.iter() { for path in &matches.free {
if !resolve_path(path, strip, zero, quiet) { if !resolve_path(path, strip, zero, quiet) {
retcode = 1 retcode = 1
}; };

View file

@ -42,7 +42,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
if matches.opt_present("V") { version(); return 0 } if matches.opt_present("V") { version(); return 0 }
if matches.opt_present("h") { show_usage(&opts); return 0 } if matches.opt_present("h") { show_usage(&opts); return 0 }
if matches.free.len() == 0 { if matches.free.is_empty() {
show_error!("Missing operand: TO"); show_error!("Missing operand: TO");
println!("Try `{} --help` for more information.", NAME); println!("Try `{} --help` for more information.", NAME);
return 1 return 1

View file

@ -126,19 +126,16 @@ pub fn uumain(args: Vec<String>) -> i32 {
fn remove(files: Vec<String>, force: bool, interactive: InteractiveMode, one_fs: bool, preserve_root: bool, recursive: bool, dir: bool, verbose: bool) -> bool { fn remove(files: Vec<String>, force: bool, interactive: InteractiveMode, one_fs: bool, preserve_root: bool, recursive: bool, dir: bool, verbose: bool) -> bool {
let mut had_err = false; let mut had_err = false;
for filename in files.iter() { for filename in &files {
let filename = &filename[..]; let filename = &filename[..];
let file = Path::new(filename); let file = Path::new(filename);
if file.exists() { if file.exists() {
if file.is_dir() { if file.is_dir() {
if recursive && (filename != "/" || !preserve_root) { if recursive && (filename != "/" || !preserve_root) {
if interactive != InteractiveMode::InteractiveAlways { if interactive != InteractiveMode::InteractiveAlways {
match fs::remove_dir_all(file) { if let Err(e) = fs::remove_dir_all(file) {
Err(e) => { had_err = true;
had_err = true; show_error!("could not remove '{}': {}", filename, e);
show_error!("could not remove '{}': {}", filename, e);
},
_ => (),
}; };
} else { } else {
let mut dirs: VecDeque<PathBuf> = VecDeque::new(); let mut dirs: VecDeque<PathBuf> = VecDeque::new();
@ -185,7 +182,7 @@ fn remove(files: Vec<String>, force: bool, interactive: InteractiveMode, one_fs:
}, },
}; };
for f in files.iter() { for f in &files {
had_err = remove_file(f.as_path(), interactive, verbose).bitor(had_err); had_err = remove_file(f.as_path(), interactive, verbose).bitor(had_err);
} }

View file

@ -69,18 +69,13 @@ Remove the DIRECTORY(ies), if they are empty.", NAME, VERSION);
fn remove(dirs: Vec<String>, ignore: bool, parents: bool, verbose: bool) -> Result<(), i32> { fn remove(dirs: Vec<String>, ignore: bool, parents: bool, verbose: bool) -> Result<(), i32> {
let mut r = Ok(()); let mut r = Ok(());
for dir in dirs.iter() { for dir in &dirs {
let path = Path::new(&dir[..]); let path = Path::new(&dir[..]);
r = remove_dir(&path, ignore, verbose).and(r); r = remove_dir(&path, ignore, verbose).and(r);
if parents { if parents {
let mut p = path; let mut p = path;
loop { while let Some(new_p) = p.parent() {
let new_p = match p.parent() {
Some(p) => p,
None => break,
};
p = new_p; p = new_p;
match p.as_os_str().to_str() { match p.as_os_str().to_str() {
None => break, None => break,
Some(s) => match s { Some(s) => match s {

View file

@ -148,7 +148,7 @@ fn print_version() {
pub fn uumain(args: Vec<String>) -> i32 { pub fn uumain(args: Vec<String>) -> i32 {
let mut options = SeqOptions { let mut options = SeqOptions {
separator: "\n".to_string(), separator: "\n".to_owned(),
terminator: None, terminator: None,
widths: false widths: false
}; };
@ -209,7 +209,6 @@ pub fn uumain(args: Vec<String>) -> i32 {
0 0
} }
#[inline(always)]
fn done_printing(next: f64, step: f64, last: f64) -> bool { fn done_printing(next: f64, step: f64, last: f64) -> bool {
if step >= 0f64 { if step >= 0f64 {
next > last next > last

View file

@ -352,7 +352,7 @@ fn wipe_file(path_str: &str, n_passes: usize, remove: bool,
let remainder = n_passes % PATTERNS.len(); // How many do we get through on our last time through? let remainder = n_passes % PATTERNS.len(); // How many do we get through on our last time through?
for _ in 0..n_full_arrays { for _ in 0..n_full_arrays {
for p in PATTERNS.iter() { for p in &PATTERNS {
pass_sequence.push(PassType::Pattern(*p)); pass_sequence.push(PassType::Pattern(*p));
} }
} }

View file

@ -79,8 +79,8 @@ With no FILE, or when FILE is -, read standard input.", NAME, VERSION);
if echo { if echo {
Mode::Echo Mode::Echo
} else { } else {
if matches.free.len() == 0 { if matches.free.is_empty() {
matches.free.push("-".to_string()); matches.free.push("-".to_owned());
} else if matches.free.len() > 1 { } else if matches.free.len() > 1 {
show_error!("extra operand '{}'", &matches.free[1][..]); show_error!("extra operand '{}'", &matches.free[1][..]);
} }
@ -212,7 +212,7 @@ fn shuf_bytes(input: &mut Vec<&[u8]>, repeat: bool, count: usize, sep: u8, outpu
drop(len); drop(len);
let mut count = count; let mut count = count;
while count > 0 && input.len() > 0 { while count > 0 && !input.is_empty() {
let mut r = input.len(); let mut r = input.len();
while r >= input.len() { while r >= input.len() {
r = rng.next_usize() % len_mod; r = rng.next_usize() % len_mod;
@ -238,7 +238,7 @@ fn shuf_bytes(input: &mut Vec<&[u8]>, repeat: bool, count: usize, sep: u8, outpu
fn parse_range(input_range: String) -> Result<(usize, usize), String> { fn parse_range(input_range: String) -> Result<(usize, usize), String> {
let split: Vec<&str> = input_range.split('-').collect(); let split: Vec<&str> = input_range.split('-').collect();
if split.len() != 2 { if split.len() != 2 {
Err("invalid range format".to_string()) Err("invalid range format".to_owned())
} else { } else {
let begin = match split[0].parse::<usize>() { let begin = match split[0].parse::<usize>() {
Ok(m) => m, Ok(m) => m,
@ -259,9 +259,9 @@ enum WrappedRng {
impl WrappedRng { impl WrappedRng {
fn next_usize(&mut self) -> usize { fn next_usize(&mut self) -> usize {
match self { match *self {
&mut WrappedRng::RngFile(ref mut r) => r.next_u32() as usize, WrappedRng::RngFile(ref mut r) => r.next_u32() as usize,
&mut WrappedRng::RngDefault(ref mut r) => r.next_u32() as usize, WrappedRng::RngDefault(ref mut r) => r.next_u32() as usize,
} }
} }
} }

View file

@ -69,7 +69,7 @@ With no FILE, or when FILE is -, read standard input.", NAME, VERSION);
let mut files = matches.free; let mut files = matches.free;
if files.is_empty() { if files.is_empty() {
/* if no file, default to stdin */ /* if no file, default to stdin */
files.push("-".to_string()); files.push("-".to_owned());
} }
exec(files, numeric, human_readable, reverse); exec(files, numeric, human_readable, reverse);
@ -78,7 +78,7 @@ With no FILE, or when FILE is -, read standard input.", NAME, VERSION);
} }
fn exec(files: Vec<String>, numeric: bool, human_readable: bool, reverse: bool) { fn exec(files: Vec<String>, numeric: bool, human_readable: bool, reverse: bool) {
for path in files.iter() { for path in &files {
let (reader, _) = match open(path) { let (reader, _) = match open(path) {
Some(x) => x, Some(x) => x,
None => continue, None => continue,
@ -114,7 +114,7 @@ fn exec(files: Vec<String>, numeric: bool, human_readable: bool, reverse: bool)
} }
/// Parse the beginning string into an f64, returning -inf instead of NaN on errors. /// Parse the beginning string into an f64, returning -inf instead of NaN on errors.
fn permissive_f64_parse(a: &String) -> f64{ fn permissive_f64_parse(a: &str) -> f64{
//Maybe should be split on non-digit, but then 10e100 won't parse properly. //Maybe should be split on non-digit, but then 10e100 won't parse properly.
//On the flip side, this will give NEG_INFINITY for "1,234", which might be OK //On the flip side, this will give NEG_INFINITY for "1,234", which might be OK
//because there's no way to handle both CSV and thousands separators without a new flag. //because there's no way to handle both CSV and thousands separators without a new flag.
@ -135,13 +135,13 @@ fn numeric_compare(a: &String, b: &String) -> Ordering {
//f64::cmp isn't implemented because NaN messes with it //f64::cmp isn't implemented because NaN messes with it
//but we sidestep that with permissive_f64_parse so just fake it //but we sidestep that with permissive_f64_parse so just fake it
if fa > fb { if fa > fb {
return Ordering::Greater; Ordering::Greater
} }
else if fa < fb { else if fa < fb {
return Ordering::Less; Ordering::Less
} }
else { else {
return Ordering::Equal; Ordering::Equal
} }
} }
@ -162,7 +162,7 @@ fn human_readable_convert(a: &String) -> f64 {
'P' => 1E15, 'P' => 1E15,
_ => 1f64 _ => 1f64
}; };
return int_part * suffix; int_part * suffix
} }
/// Compare two strings as if they are human readable sizes. /// Compare two strings as if they are human readable sizes.
@ -171,18 +171,17 @@ fn human_readable_size_compare(a: &String, b: &String) -> Ordering {
let fa = human_readable_convert(a); let fa = human_readable_convert(a);
let fb = human_readable_convert(b); let fb = human_readable_convert(b);
if fa > fb { if fa > fb {
return Ordering::Greater; Ordering::Greater
} }
else if fa < fb { else if fa < fb {
return Ordering::Less; Ordering::Less
} }
else { else {
return Ordering::Equal; Ordering::Equal
} }
} }
#[inline(always)]
fn print_sorted<S, T: Iterator<Item=S>>(iter: T) where S: std::fmt::Display { fn print_sorted<S, T: Iterator<Item=S>>(iter: T) where S: std::fmt::Display {
for line in iter { for line in iter {
println!("{}", line); println!("{}", line);
@ -190,7 +189,7 @@ fn print_sorted<S, T: Iterator<Item=S>>(iter: T) where S: std::fmt::Display {
} }
// from cat.rs // from cat.rs
fn open<'a>(path: &str) -> Option<(Box<Read + 'a>, bool)> { fn open(path: &str) -> Option<(Box<Read>, bool)> {
if path == "-" { if path == "-" {
let stdin = stdin(); let stdin = stdin();
return Some((Box::new(stdin) as Box<Read>, is_stdin_interactive())); return Some((Box::new(stdin) as Box<Read>, is_stdin_interactive()));

View file

@ -60,16 +60,16 @@ size is 1000, and default PREFIX is 'x'. With no INPUT, or when INPUT is
} }
let mut settings = Settings { let mut settings = Settings {
prefix: "".to_string(), prefix: "".to_owned(),
numeric_suffix: false, numeric_suffix: false,
suffix_length: 0, suffix_length: 0,
input: "".to_string(), input: "".to_owned(),
strategy: "".to_string(), strategy: "".to_owned(),
strategy_param: "".to_string(), strategy_param: "".to_owned(),
verbose: false, verbose: false,
}; };
settings.numeric_suffix = if matches.opt_present("d") { true } else { false }; settings.numeric_suffix = matches.opt_present("d");
settings.suffix_length = match matches.opt_str("a") { settings.suffix_length = match matches.opt_str("a") {
Some(n) => match n.parse() { Some(n) => match n.parse() {
@ -79,16 +79,16 @@ size is 1000, and default PREFIX is 'x'. With no INPUT, or when INPUT is
None => 2 None => 2
}; };
settings.verbose = if matches.opt_present("verbose") { true } else { false }; settings.verbose = matches.opt_present("verbose");
settings.strategy = "l".to_string(); settings.strategy = "l".to_owned();
settings.strategy_param = "1000".to_string(); settings.strategy_param = "1000".to_owned();
let strategies = vec!["b", "C", "l"]; let strategies = vec!["b", "C", "l"];
for e in strategies.iter() { for e in &strategies {
match matches.opt_str(*e) { match matches.opt_str(*e) {
Some(a) => { Some(a) => {
if settings.strategy == "l" { if settings.strategy == "l" {
settings.strategy = e.to_string(); settings.strategy = (*e).to_owned();
settings.strategy_param = a; settings.strategy_param = a;
} else { } else {
crash!(1, "{}: cannot split in more than one way", NAME) crash!(1, "{}: cannot split in more than one way", NAME)
@ -100,9 +100,9 @@ size is 1000, and default PREFIX is 'x'. With no INPUT, or when INPUT is
let mut v = matches.free.iter(); let mut v = matches.free.iter();
let (input, prefix) = match (v.next(), v.next()) { let (input, prefix) = match (v.next(), v.next()) {
(Some(a), None) => (a.to_string(), "x".to_string()), (Some(a), None) => (a.to_owned(), "x".to_owned()),
(Some(a), Some(b)) => (a.to_string(), b.to_string()), (Some(a), Some(b)) => (a.clone(), b.clone()),
(None, _) => ("-".to_string(), "x".to_string()), (None, _) => ("-".to_owned(), "x".to_owned()),
}; };
settings.input = input; settings.input = input;
settings.prefix = prefix; settings.prefix = prefix;
@ -179,7 +179,7 @@ impl ByteSplitter {
_ => crash!(1, "invalid number of bytes") _ => crash!(1, "invalid number of bytes")
}; };
let n = if suffix.is_alphabetic() { let n = if suffix.is_alphabetic() {
match strategy_param.iter().map(|c| *c).collect::<String>().parse::<usize>() { match strategy_param.iter().cloned().collect::<String>().parse::<usize>() {
Ok(a) => a, Ok(a) => a,
Err(e) => crash!(1, "invalid number of bytes: {}", e) Err(e) => crash!(1, "invalid number of bytes: {}", e)
} }
@ -192,7 +192,7 @@ impl ByteSplitter {
Box::new(ByteSplitter { Box::new(ByteSplitter {
saved_bytes_to_write: n * multiplier, saved_bytes_to_write: n * multiplier,
bytes_to_write: n * multiplier, bytes_to_write: n * multiplier,
break_on_line_end: if settings.strategy == "b" { false } else { true }, break_on_line_end: settings.strategy == "b",
require_whole_line: false, require_whole_line: false,
}) as Box<Splitter> }) as Box<Splitter>
} }
@ -206,7 +206,7 @@ impl Splitter for ByteSplitter {
self.bytes_to_write = self.saved_bytes_to_write; self.bytes_to_write = self.saved_bytes_to_write;
control.request_new_file = true; control.request_new_file = true;
self.require_whole_line = false; self.require_whole_line = false;
return line[0..0].to_string(); return line[0..0].to_owned();
} }
self.bytes_to_write -= n; self.bytes_to_write -= n;
if n == 0 { if n == 0 {
@ -216,13 +216,13 @@ impl Splitter for ByteSplitter {
if self.break_on_line_end && n == line.chars().count() { if self.break_on_line_end && n == line.chars().count() {
self.require_whole_line = self.break_on_line_end; self.require_whole_line = self.break_on_line_end;
} }
line[..n].to_string() line[..n].to_owned()
} }
} }
// (1, 3) -> "aab" // (1, 3) -> "aab"
fn str_prefix(i: usize, width: usize) -> String { fn str_prefix(i: usize, width: usize) -> String {
let mut c = "".to_string(); let mut c = "".to_owned();
let mut n = i; let mut n = i;
let mut w = width; let mut w = width;
while w > 0 { while w > 0 {
@ -237,7 +237,7 @@ fn str_prefix(i: usize, width: usize) -> String {
// (1, 3) -> "001" // (1, 3) -> "001"
fn num_prefix(i: usize, width: usize) -> String { fn num_prefix(i: usize, width: usize) -> String {
let mut c = "".to_string(); let mut c = "".to_owned();
let mut n = i; let mut n = i;
let mut w = width; let mut w = width;
while w > 0 { while w > 0 {
@ -267,11 +267,11 @@ fn split(settings: &Settings) -> i32 {
match settings.strategy.as_ref() { match settings.strategy.as_ref() {
"l" => LineSplitter::new(settings), "l" => LineSplitter::new(settings),
"b" | "C" => ByteSplitter::new(settings), "b" | "C" => ByteSplitter::new(settings),
a @ _ => crash!(1, "strategy {} not supported", a) a => crash!(1, "strategy {} not supported", a)
}; };
let mut control = SplitControl { let mut control = SplitControl {
current_line: "".to_string(), // Request new line current_line: "".to_owned(), // Request new line
request_new_file: true, // Request new file request_new_file: true, // Request new file
}; };
@ -310,7 +310,7 @@ fn split(settings: &Settings) -> i32 {
let advance = consumed.chars().count(); let advance = consumed.chars().count();
let clone = control.current_line.clone(); let clone = control.current_line.clone();
let sl = clone; let sl = clone;
control.current_line = sl[advance..sl.chars().count()].to_string(); control.current_line = sl[advance..sl.chars().count()].to_owned();
} }
0 0
} }

View file

@ -93,7 +93,7 @@ fn print_usage(opts: &Options) {
fn parse_size(size: &str) -> Option<u64> { fn parse_size(size: &str) -> Option<u64> {
let ext = size.trim_left_matches(|c: char| c.is_digit(10)); let ext = size.trim_left_matches(|c: char| c.is_digit(10));
let num = size.trim_right_matches(|c: char| c.is_alphabetic()); let num = size.trim_right_matches(|c: char| c.is_alphabetic());
let mut recovered = num.to_string(); let mut recovered = num.to_owned();
recovered.push_str(ext); recovered.push_str(ext);
if recovered != size { if recovered != size {
return None; return None;
@ -196,19 +196,19 @@ fn exe_path() -> io::Result<PathBuf> {
fn get_preload_env() -> (String, String) { fn get_preload_env() -> (String, String) {
let (preload, extension) = preload_strings(); let (preload, extension) = preload_strings();
let mut libstdbuf = LIBSTDBUF.to_string(); let mut libstdbuf = LIBSTDBUF.to_owned();
libstdbuf.push_str(extension); libstdbuf.push_str(extension);
// First search for library in directory of executable. // First search for library in directory of executable.
let mut path = exe_path().unwrap_or_else(|_| crash!(1, "Impossible to fetch the path of this executable.")); let mut path = exe_path().unwrap_or_else(|_| crash!(1, "Impossible to fetch the path of this executable."));
path.push(libstdbuf.clone()); path.push(libstdbuf.clone());
if path.exists() { if path.exists() {
match path.as_os_str().to_str() { match path.as_os_str().to_str() {
Some(s) => { return (preload.to_string(), s.to_string()); }, Some(s) => { return (preload.to_owned(), s.to_owned()); },
None => crash!(1, "Error while converting path.") None => crash!(1, "Error while converting path.")
}; };
} }
// We assume library is in LD_LIBRARY_PATH/ DYLD_LIBRARY_PATH. // We assume library is in LD_LIBRARY_PATH/ DYLD_LIBRARY_PATH.
(preload.to_string(), libstdbuf) (preload.to_owned(), libstdbuf)
} }
pub fn uumain(args: Vec<String>) -> i32 { pub fn uumain(args: Vec<String>) -> i32 {
@ -243,7 +243,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
if command_idx == -1 { if command_idx == -1 {
crash!(125, "Invalid options\nTry 'stdbuf --help' for more information."); crash!(125, "Invalid options\nTry 'stdbuf --help' for more information.");
} }
let ref command_name = args[command_idx as usize]; let command_name = &args[command_idx as usize];
let mut command = Command::new(command_name); let mut command = Command::new(command_name);
let (preload_env, libstdbuf) = get_preload_env(); let (preload_env, libstdbuf) = get_preload_env();
command.args(&args[(command_idx as usize) + 1 ..]).env(preload_env, libstdbuf); command.args(&args[(command_idx as usize) + 1 ..]).env(preload_env, libstdbuf);

View file

@ -106,7 +106,7 @@ Checksum and count the blocks in a file.", NAME, VERSION);
let sysv = matches.opt_present("sysv"); let sysv = matches.opt_present("sysv");
let files = if matches.free.is_empty() { let files = if matches.free.is_empty() {
vec!["-".to_string()] vec!["-".to_owned()]
} else { } else {
matches.free matches.free
}; };
@ -117,7 +117,7 @@ Checksum and count the blocks in a file.", NAME, VERSION);
files.len() > 1 files.len() > 1
}; };
for file in files.iter() { for file in &files {
let reader = match open(file) { let reader = match open(file) {
Ok(f) => f, Ok(f) => f,
_ => crash!(1, "unable to open file") _ => crash!(1, "unable to open file")

View file

@ -50,16 +50,16 @@ Write each file to standard output, last line first.", NAME, VERSION);
let regex = matches.opt_present("r"); let regex = matches.opt_present("r");
let separator = match matches.opt_str("s") { let separator = match matches.opt_str("s") {
Some(m) => { Some(m) => {
if m.len() == 0 { if m.is_empty() {
crash!(1, "separator cannot be empty") crash!(1, "separator cannot be empty")
} else { } else {
m m
} }
} }
None => "\n".to_string() None => "\n".to_owned()
}; };
let files = if matches.free.is_empty() { let files = if matches.free.is_empty() {
vec!("-".to_string()) vec!("-".to_owned())
} else { } else {
matches.free matches.free
}; };
@ -74,7 +74,7 @@ fn tac(filenames: Vec<String>, before: bool, _: bool, separator: &str) {
let sbytes = separator.as_bytes(); let sbytes = separator.as_bytes();
let slen = sbytes.len(); let slen = sbytes.len();
for filename in filenames.iter() { for filename in &filenames {
let mut file = BufReader::new( let mut file = BufReader::new(
if filename == "-" { if filename == "-" {
Box::new(stdin()) as Box<Read> Box::new(stdin()) as Box<Read>
@ -115,7 +115,7 @@ fn tac(filenames: Vec<String>, before: bool, _: bool, separator: &str) {
drop(i); drop(i);
// if there isn't a separator at the end of the file, fake it // if there isn't a separator at the end of the file, fake it
if offsets.len() == 0 || *offsets.last().unwrap() < data.len() - slen { if offsets.is_empty() || *offsets.last().unwrap() < data.len() - slen {
offsets.push(data.len()); offsets.push(data.len());
} }

View file

@ -144,7 +144,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
multiple = true; multiple = true;
} }
for file in files.iter() { for file in &files {
if multiple { if multiple {
if !firstime { println!(""); } if !firstime { println!(""); }
println!("==> {} <==", file); println!("==> {} <==", file);
@ -280,7 +280,7 @@ fn tail<T: Read>(reader: &mut BufReader<T>, settings: &Settings) {
} }
} }
let mut stdout = stdout(); let mut stdout = stdout();
for datum in ringbuf.iter() { for datum in &ringbuf {
print_string(&mut stdout, datum); print_string(&mut stdout, datum);
} }
}, },
@ -311,7 +311,7 @@ fn tail<T: Read>(reader: &mut BufReader<T>, settings: &Settings) {
} }
} }
let mut stdout = stdout(); let mut stdout = stdout();
for datum in ringbuf.iter() { for datum in &ringbuf {
print_byte(&mut stdout, datum); print_byte(&mut stdout, datum);
} }
} }
@ -339,7 +339,7 @@ fn print_byte<T: Write>(stdout: &mut T, ch: &u8) {
} }
#[inline] #[inline]
fn print_string<T: Write>(_: &mut T, s: &String) { fn print_string<T: Write>(_: &mut T, s: &str) {
print!("{}", s); print!("{}", s);
} }

View file

@ -37,7 +37,7 @@ struct Options {
files: Vec<String> files: Vec<String>
} }
fn options(args: &Vec<String>) -> Result<Options> { fn options(args: &[String]) -> Result<Options> {
let mut opts = getopts::Options::new(); let mut opts = getopts::Options::new();
opts.optflag("a", "append", "append to the given FILEs, do not overwrite"); opts.optflag("a", "append", "append to the given FILEs, do not overwrite");
@ -54,12 +54,12 @@ fn options(args: &Vec<String>) -> Result<Options> {
version, NAME, arguments, opts.usage(brief), version, NAME, arguments, opts.usage(brief),
comment); comment);
let mut names: Vec<String> = m.free.clone().into_iter().collect(); let mut names: Vec<String> = m.free.clone().into_iter().collect();
names.push("-".to_string()); names.push("-".to_owned());
let to_print = if m.opt_present("help") { Some(help) } let to_print = if m.opt_present("help") { Some(help) }
else if m.opt_present("version") { Some(version) } else if m.opt_present("version") { Some(version) }
else { None }; else { None };
Ok(Options { Ok(Options {
program: NAME.to_string(), program: NAME.to_owned(),
append: m.opt_present("append"), append: m.opt_present("append"),
ignore_interrupts: m.opt_present("ignore-interrupts"), ignore_interrupts: m.opt_present("ignore-interrupts"),
print_and_exit: to_print, print_and_exit: to_print,
@ -108,14 +108,14 @@ struct MultiWriter {
impl Write for MultiWriter { impl Write for MultiWriter {
fn write(&mut self, buf: &[u8]) -> Result<usize> { fn write(&mut self, buf: &[u8]) -> Result<usize> {
for writer in self.writers.iter_mut() { for writer in &mut self.writers {
try!(writer.write_all(buf)); try!(writer.write_all(buf));
} }
Ok(buf.len()) Ok(buf.len())
} }
fn flush(&mut self) -> Result<()> { fn flush(&mut self) -> Result<()> {
for writer in self.writers.iter_mut() { for writer in &mut self.writers {
try!(writer.flush()); try!(writer.flush());
} }
Ok(()) Ok(())

View file

@ -24,7 +24,7 @@ pub fn uumain(_: Vec<String>) -> i32 {
let args = args_os().collect::<Vec<OsString>>(); let args = args_os().collect::<Vec<OsString>>();
// This is completely disregarding valid windows paths that aren't valid unicode // This is completely disregarding valid windows paths that aren't valid unicode
let args = args.iter().map(|a| a.to_str().unwrap().as_bytes()).collect::<Vec<&[u8]>>(); let args = args.iter().map(|a| a.to_str().unwrap().as_bytes()).collect::<Vec<&[u8]>>();
if args.len() == 0 { if args.is_empty() {
return 2; return 2;
} }
let args = let args =
@ -145,7 +145,7 @@ fn integers(a: &[u8], b: &[u8], cond: IntegerCondition) -> bool {
fn isatty(fd: &[u8]) -> bool { fn isatty(fd: &[u8]) -> bool {
use libc::{isatty}; use libc::{isatty};
from_utf8(fd).ok().and_then(|s| s.parse().ok()) from_utf8(fd).ok().and_then(|s| s.parse().ok())
.map(|i| unsafe { isatty(i) == 1 }).unwrap_or(false) .map_or(false, |i| unsafe { isatty(i) == 1 })
} }
fn dispatch(args: &mut &[&[u8]], error: &mut bool) -> bool { fn dispatch(args: &mut &[&[u8]], error: &mut bool) -> bool {
@ -347,7 +347,7 @@ fn path(path: &[u8], cond: PathCondition) -> bool {
} else if gid == stat.st_gid { } else if gid == stat.st_gid {
stat.st_mode & ((p as mode_t) << 3) != 0 stat.st_mode & ((p as mode_t) << 3) != 0
} else { } else {
stat.st_mode & ((p as mode_t) << 0) != 0 stat.st_mode & ((p as mode_t)) != 0
} }
}; };

View file

@ -137,7 +137,7 @@ fn timeout(cmdname: &str, args: &[String], duration: f64, signal: usize, kill_af
return_if_err!(ERR_EXIT_STATUS, process.wait()); return_if_err!(ERR_EXIT_STATUS, process.wait());
137 137
}, },
Err(_) => return 124, Err(_) => 124,
} }
}, },
Err(_) => { Err(_) => {

View file

@ -83,16 +83,16 @@ pub fn uumain(args: Vec<String>) -> i32 {
return 0; return 0;
} }
if matches.opt_present("date") && matches.opts_present(&["reference".to_string(), "t".to_string()]) || if matches.opt_present("date") && matches.opts_present(&["reference".to_owned(), "t".to_owned()]) ||
matches.opt_present("reference") && matches.opts_present(&["date".to_string(), "t".to_string()]) || matches.opt_present("reference") && matches.opts_present(&["date".to_owned(), "t".to_owned()]) ||
matches.opt_present("t") && matches.opts_present(&["date".to_string(), "reference".to_string()]) { matches.opt_present("t") && matches.opts_present(&["date".to_owned(), "reference".to_owned()]) {
panic!("Invalid options: cannot specify reference time from more than one source"); panic!("Invalid options: cannot specify reference time from more than one source");
} }
let (mut atime, mut mtime) = let (mut atime, mut mtime) =
if matches.opt_present("reference") { if matches.opt_present("reference") {
stat(&matches.opt_str("reference").unwrap()[..], !matches.opt_present("no-dereference")) stat(&matches.opt_str("reference").unwrap()[..], !matches.opt_present("no-dereference"))
} else if matches.opts_present(&["date".to_string(), "t".to_string()]) { } else if matches.opts_present(&["date".to_owned(), "t".to_owned()]) {
let timestamp = if matches.opt_present("date") { let timestamp = if matches.opt_present("date") {
parse_date(matches.opt_str("date").unwrap().as_ref()) parse_date(matches.opt_str("date").unwrap().as_ref())
} else { } else {
@ -104,54 +104,50 @@ pub fn uumain(args: Vec<String>) -> i32 {
(now, now) (now, now)
}; };
for filename in matches.free.iter() { for filename in &matches.free {
let path = &filename[..]; let path = &filename[..];
if !Path::new(path).exists() { if !Path::new(path).exists() {
// no-dereference included here for compatibility // no-dereference included here for compatibility
if matches.opts_present(&["no-create".to_string(), "no-dereference".to_string()]) { if matches.opts_present(&["no-create".to_owned(), "no-dereference".to_owned()]) {
continue; continue;
} }
match File::create(path) { if let Err(e) = File::create(path) {
Err(e) => { show_warning!("cannot touch '{}': {}", path, e);
show_warning!("cannot touch '{}': {}", path, e); continue;
continue;
},
_ => (),
}; };
// Minor optimization: if no reference time was specified, we're done. // Minor optimization: if no reference time was specified, we're done.
if !matches.opts_present(&["date".to_string(), "reference".to_string(), "t".to_string()]) { if !matches.opts_present(&["date".to_owned(), "reference".to_owned(), "t".to_owned()]) {
continue; continue;
} }
} }
// If changing "only" atime or mtime, grab the existing value of the other. // If changing "only" atime or mtime, grab the existing value of the other.
// Note that "-a" and "-m" may be passed together; this is not an xor. // Note that "-a" and "-m" may be passed together; this is not an xor.
if matches.opts_present(&["a".to_string(), "m".to_string(), "time".to_string()]) { if matches.opts_present(&["a".to_owned(), "m".to_owned(), "time".to_owned()]) {
let st = stat(path, !matches.opt_present("no-dereference")); let st = stat(path, !matches.opt_present("no-dereference"));
let time = matches.opt_strs("time"); let time = matches.opt_strs("time");
if !(matches.opt_present("a") || if !(matches.opt_present("a") ||
time.contains(&"access".to_string()) || time.contains(&"access".to_owned()) ||
time.contains(&"atime".to_string()) || time.contains(&"atime".to_owned()) ||
time.contains(&"use".to_string())) { time.contains(&"use".to_owned())) {
atime = st.0; atime = st.0;
} }
if !(matches.opt_present("m") || if !(matches.opt_present("m") ||
time.contains(&"modify".to_string()) || time.contains(&"modify".to_owned()) ||
time.contains(&"mtime".to_string())) { time.contains(&"mtime".to_owned())) {
mtime = st.1; mtime = st.1;
} }
} }
// this follows symlinks and thus does not work correctly for the -h flag // this follows symlinks and thus does not work correctly for the -h flag
// need to use lutimes() c function on supported platforms // need to use lutimes() c function on supported platforms
match filetime::set_file_times(path, atime, mtime) { if let Err(e) = filetime::set_file_times(path, atime, mtime) {
Err(e) => show_warning!("cannot touch '{}': {}", path, e), show_warning!("cannot touch '{}': {}", path, e);
_ => (),
}; };
} }
@ -188,10 +184,10 @@ fn parse_date(str: &str) -> FileTime {
fn parse_timestamp(s: &str) -> FileTime { fn parse_timestamp(s: &str) -> FileTime {
let now = time::now(); let now = time::now();
let (format, ts) = match s.chars().count() { let (format, ts) = match s.chars().count() {
15 => ("%Y%m%d%H%M.%S", s.to_string()), 15 => ("%Y%m%d%H%M.%S", s.to_owned()),
12 => ("%Y%m%d%H%M", s.to_string()), 12 => ("%Y%m%d%H%M", s.to_owned()),
13 => ("%y%m%d%H%M.%S", s.to_string()), 13 => ("%y%m%d%H%M.%S", s.to_owned()),
10 => ("%y%m%d%H%M", s.to_string()), 10 => ("%y%m%d%H%M", s.to_owned()),
11 => ("%Y%m%d%H%M.%S", format!("{}{}", now.tm_year + 1900, s)), 11 => ("%Y%m%d%H%M.%S", format!("{}{}", now.tm_year + 1900, s)),
8 => ("%Y%m%d%H%M", format!("{}{}", now.tm_year + 1900, s)), 8 => ("%Y%m%d%H%M", format!("{}{}", now.tm_year + 1900, s)),
_ => panic!("Unknown timestamp format") _ => panic!("Unknown timestamp format")

View file

@ -81,9 +81,8 @@ impl<'a> Iterator for ExpandSet<'a> {
// while the Range has elements, try to return chars from it // while the Range has elements, try to return chars from it
// but make sure that they actually turn out to be Chars! // but make sure that they actually turn out to be Chars!
while let Some(n) = self.range.next() { while let Some(n) = self.range.next() {
match from_u32(n) { if let Some(c) = from_u32(n) {
Some(c) => return Some(c), return Some(c);
_ => (),
} }
} }

View file

@ -32,7 +32,7 @@ static NAME: &'static str = "tr";
static VERSION: &'static str = env!("CARGO_PKG_VERSION"); static VERSION: &'static str = env!("CARGO_PKG_VERSION");
const BUFFER_LEN: usize = 1024; const BUFFER_LEN: usize = 1024;
fn delete<'a>(set: ExpandSet<'a>, complement: bool) { fn delete(set: ExpandSet, complement: bool) {
let mut bset = BitSet::new(); let mut bset = BitSet::new();
let mut stdout = stdout(); let mut stdout = stdout();
let mut buf = String::with_capacity(BUFFER_LEN + 4); let mut buf = String::with_capacity(BUFFER_LEN + 4);
@ -59,7 +59,7 @@ fn delete<'a>(set: ExpandSet<'a>, complement: bool) {
safe_unwrap!(stdout.write_all(&buf[..].as_bytes())); safe_unwrap!(stdout.write_all(&buf[..].as_bytes()));
} }
} }
if buf.len() > 0 { if !buf.is_empty() {
safe_unwrap!(stdout.write_all(&buf[..].as_bytes())); safe_unwrap!(stdout.write_all(&buf[..].as_bytes()));
pipe_flush!(); pipe_flush!();
} }
@ -95,7 +95,7 @@ fn tr<'a>(set1: ExpandSet<'a>, mut set2: ExpandSet<'a>) {
} }
} }
} }
if buf.len() > 0 { if !buf.is_empty() {
safe_unwrap!(stdout.write_all(&buf[..].as_bytes())); safe_unwrap!(stdout.write_all(&buf[..].as_bytes()));
pipe_flush!(); pipe_flush!();
} }
@ -137,13 +137,13 @@ pub fn uumain(args: Vec<String>) -> i32 {
return 0; return 0;
} }
if matches.free.len() == 0 { if matches.free.is_empty() {
usage(&opts); usage(&opts);
return 1; return 1;
} }
let dflag = matches.opt_present("d"); let dflag = matches.opt_present("d");
let cflag = matches.opts_present(&["c".to_string(), "C".to_string()]); let cflag = matches.opts_present(&["c".to_owned(), "C".to_owned()]);
let sets = matches.free; let sets = matches.free;
if cflag && !dflag { if cflag && !dflag {

View file

@ -115,7 +115,7 @@ fn truncate(no_create: bool, _: bool, reference: Option<String>, size: Option<St
} }
None => parse_size(size.unwrap().as_ref()) None => parse_size(size.unwrap().as_ref())
}; };
for filename in filenames.iter() { for filename in &filenames {
let path = Path::new(filename); let path = Path::new(filename);
match OpenOptions::new().read(true).write(true).create(!no_create).open(path) { match OpenOptions::new().read(true).write(true).create(!no_create).open(path) {
Ok(file) => { Ok(file) => {
@ -135,7 +135,7 @@ fn truncate(no_create: bool, _: bool, reference: Option<String>, size: Option<St
TruncateMode::RoundDown => fsize - fsize % refsize, TruncateMode::RoundDown => fsize - fsize % refsize,
TruncateMode::RoundUp => fsize + fsize % refsize TruncateMode::RoundUp => fsize + fsize % refsize
}; };
let _ = match file.set_len(tsize) { match file.set_len(tsize) {
Ok(_) => {}, Ok(_) => {},
Err(f) => { Err(f) => {
crash!(1, "{}", f.to_string()) crash!(1, "{}", f.to_string())
@ -163,7 +163,6 @@ fn parse_size(size: &str) -> (u64, TruncateMode) {
let bytes = { let bytes = {
let mut slice = let mut slice =
if mode == TruncateMode::Reference { if mode == TruncateMode::Reference {
let size: &str = size;
size size
} else { } else {
&size[1..] &size[1..]
@ -175,7 +174,7 @@ fn parse_size(size: &str) -> (u64, TruncateMode) {
} }
} }
slice slice
}.to_string(); }.to_owned();
let mut number: u64 = match bytes.parse() { let mut number: u64 = match bytes.parse() {
Ok(num) => num, Ok(num) => num,
Err(e) => { Err(e) => {

View file

@ -54,9 +54,9 @@ pub fn uumain(args: Vec<String>) -> i32 {
let input = if files.len() > 1 { let input = if files.len() > 1 {
crash!(1, "{}, extra operand '{}'", NAME, matches.free[1]); crash!(1, "{}, extra operand '{}'", NAME, matches.free[1]);
} else if files.is_empty() { } else if files.is_empty() {
"-".to_string() "-".to_owned()
} else { } else {
files[0].to_string() files[0].clone()
}; };
let mut stdin_buf; let mut stdin_buf;
@ -82,8 +82,8 @@ pub fn uumain(args: Vec<String>) -> i32 {
let mut line = String::new(); let mut line = String::new();
match reader.read_line(&mut line) { match reader.read_line(&mut line) {
Ok(_) => { Ok(_) => {
let tokens: Vec<String> = line.trim_right().split_whitespace().map(|s| s.to_string()).collect(); let tokens: Vec<String> = line.trim_right().split_whitespace().map(|s| s.to_owned()).collect();
if tokens.len() == 0 { if tokens.is_empty() {
break break
} }
for ab in tokens.chunks(2) { for ab in tokens.chunks(2) {
@ -103,7 +103,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
crash!(1, "{}, input contains a loop:", input); crash!(1, "{}, input contains a loop:", input);
} }
for x in g.result.iter() { for x in &g.result {
println!("{}", x); println!("{}", x);
} }
@ -127,11 +127,11 @@ impl Graph {
} }
} }
fn has_node(&self, n: &String) -> bool { fn has_node(&self, n: &str) -> bool {
self.in_edges.contains_key(n) self.in_edges.contains_key(n)
} }
fn has_edge(&self, from: &String, to: &String) -> bool { fn has_edge(&self, from: &str, to: &str) -> bool {
self.in_edges.get(to).unwrap().contains(from) self.in_edges.get(to).unwrap().contains(from)
} }
@ -159,7 +159,7 @@ impl Graph {
// O(|V|+|E|) // O(|V|+|E|)
fn run_tsort(&mut self) { fn run_tsort(&mut self) {
let mut start_nodes = vec!(); let mut start_nodes = vec!();
for (n, edges) in self.in_edges.iter() { for (n, edges) in &self.in_edges {
if edges.is_empty() { if edges.is_empty() {
start_nodes.push(n.clone()); start_nodes.push(n.clone());
} }
@ -185,7 +185,7 @@ impl Graph {
} }
fn is_acyclic(&self) -> bool { fn is_acyclic(&self) -> bool {
for (_, edges) in self.out_edges.iter() { for (_, edges) in &self.out_edges {
if !edges.is_empty() { if !edges.is_empty() {
return false return false
} }

View file

@ -57,7 +57,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
if !ptr.is_null() { if !ptr.is_null() {
String::from_utf8_lossy(CStr::from_ptr(ptr).to_bytes()).to_string() String::from_utf8_lossy(CStr::from_ptr(ptr).to_bytes()).to_string()
} else { } else {
"".to_string() "".to_owned()
} }
}; };

View file

@ -81,7 +81,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
let uname = unsafe { getuname() }; let uname = unsafe { getuname() };
let mut output = String::new(); let mut output = String::new();
if matches.opt_present("sysname") || matches.opt_present("all") if matches.opt_present("sysname") || matches.opt_present("all")
|| !matches.opts_present(&["nodename".to_string(), "release".to_string(), "version".to_string(), "machine".to_string()]) { || !matches.opts_present(&["nodename".to_owned(), "release".to_owned(), "version".to_owned(), "machine".to_owned()]) {
output.push_str(uname.sysname.as_ref()); output.push_str(uname.sysname.as_ref());
output.push_str(" "); output.push_str(" ");
} }

View file

@ -45,9 +45,8 @@ fn tabstops_parse(s: String) -> Vec<usize> {
crash!(1, "{}\n", "tab size cannot be 0"); crash!(1, "{}\n", "tab size cannot be 0");
} }
match nums.iter().fold((true, 0), |(acc, last), &n| (acc && last <= n, n)) { if let (false, _) = nums.iter().fold((true, 0), |(acc, last), &n| (acc && last <= n, n)) {
(false, _) => crash!(1, "{}\n", "tab sizes must be ascending"), crash!(1, "{}\n", "tab sizes must be ascending");
_ => {}
} }
nums nums
@ -73,7 +72,7 @@ impl Options {
let files = let files =
if matches.free.is_empty() { if matches.free.is_empty() {
vec!("-".to_string()) vec!("-".to_owned())
} else { } else {
matches.free matches.free
}; };
@ -191,7 +190,7 @@ fn unexpand(options: Options) {
while match fh.read_until('\n' as u8, &mut buf) { while match fh.read_until('\n' as u8, &mut buf) {
Ok(s) => s > 0, Ok(s) => s > 0,
Err(_) => buf.len() > 0, Err(_) => !buf.is_empty(),
} { } {
let mut byte = 0; // offset into the buffer let mut byte = 0; // offset into the buffer
let mut col = 0; // the current column let mut col = 0; // the current column

View file

@ -58,7 +58,7 @@ impl Uniq {
} }
} }
fn skip_fields(&self, line: &String) -> String { fn skip_fields(&self, line: &str) -> String {
match self.skip_fields { match self.skip_fields {
Some(skip_fields) => Some(skip_fields) =>
if line.split_whitespace().count() > skip_fields { if line.split_whitespace().count() > skip_fields {
@ -73,15 +73,15 @@ impl Uniq {
} }
field = field + 1; field = field + 1;
} }
line[i..].to_string() line[i..].to_owned()
} else { } else {
"".to_string() "".to_owned()
}, },
None => line[..].to_string() None => line[..].to_owned()
} }
} }
fn cmp_key(&self, line: &String) -> String { fn cmp_key(&self, line: &str) -> String {
let len = line.len(); let len = line.len();
if len > 0 { if len > 0 {
let slice_start = match self.slice_start { let slice_start = match self.slice_start {
@ -99,11 +99,11 @@ impl Uniq {
_ => c, _ => c,
}).collect() }).collect()
} else { } else {
line.clone() line.to_owned()
} }
} }
fn print_lines<W: Write>(&self, writer: &mut BufWriter<W>, lines: &Vec<String>, print_delimiter: bool) -> bool { fn print_lines<W: Write>(&self, writer: &mut BufWriter<W>, lines: &[String], print_delimiter: bool) -> bool {
let mut first_line_printed = false; let mut first_line_printed = false;
let mut count = if self.all_repeated { 1 } else { lines.len() }; let mut count = if self.all_repeated { 1 } else { lines.len() };
if lines.len() == 1 && !self.repeats_only if lines.len() == 1 && !self.repeats_only
@ -122,7 +122,7 @@ impl Uniq {
first_line_printed first_line_printed
} }
fn print_line<W: Write>(&self, writer: &mut BufWriter<W>, line: &String, count: usize, print_delimiter: bool) { fn print_line<W: Write>(&self, writer: &mut BufWriter<W>, line: &str, count: usize, print_delimiter: bool) {
if print_delimiter { if print_delimiter {
crash_if_err!(1, writer.write_all(&['\n' as u8])); crash_if_err!(1, writer.write_all(&['\n' as u8]));
} }
@ -183,8 +183,8 @@ pub fn uumain(args: Vec<String>) -> i32 {
println!("{} {}", NAME, VERSION); println!("{} {}", NAME, VERSION);
} else { } else {
let (in_file_name, out_file_name) = match matches.free.len() { let (in_file_name, out_file_name) = match matches.free.len() {
0 => ("-".to_string(), "-".to_string()), 0 => ("-".to_owned(), "-".to_owned()),
1 => (matches.free[0].clone(), "-".to_string()), 1 => (matches.free[0].clone(), "-".to_owned()),
2 => (matches.free[0].clone(), matches.free[1].clone()), 2 => (matches.free[0].clone(), matches.free[1].clone()),
_ => { _ => {
crash!(1, "Extra operand: {}", matches.free[2]); crash!(1, "Extra operand: {}", matches.free[2]);
@ -196,13 +196,13 @@ pub fn uumain(args: Vec<String>) -> i32 {
all_repeated: matches.opt_present("all-repeated"), all_repeated: matches.opt_present("all-repeated"),
delimiters: match matches.opt_default("all-repeated", "none") { delimiters: match matches.opt_default("all-repeated", "none") {
Some(ref opt_arg) if opt_arg != "none" => { Some(ref opt_arg) if opt_arg != "none" => {
let rep_args = ["prepend".to_string(), "separate".to_string()]; let rep_args = ["prepend".to_owned(), "separate".to_owned()];
if !rep_args.contains(opt_arg) { if !rep_args.contains(opt_arg) {
crash!(1, "Incorrect argument for all-repeated: {}", opt_arg.clone()); crash!(1, "Incorrect argument for all-repeated: {}", opt_arg.clone());
} }
opt_arg.clone() opt_arg.clone()
}, },
_ => "".to_string() _ => "".to_owned()
}, },
show_counts: matches.opt_present("count"), show_counts: matches.opt_present("count"),
skip_fields: opt_parsed("skip-fields", &matches), skip_fields: opt_parsed("skip-fields", &matches),

View file

@ -52,7 +52,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
return 0; return 0;
} }
if matches.free.len() == 0 { if matches.free.is_empty() {
crash!(1, "missing operand\nTry '{0} --help' for more information.", NAME); crash!(1, "missing operand\nTry '{0} --help' for more information.", NAME);
} else if matches.free.len() > 1 { } else if matches.free.len() > 1 {
crash!(1, "extra operand: '{1}'\nTry '{0} --help' for more information.", NAME, matches.free[1]); crash!(1, "extra operand: '{1}'\nTry '{0} --help' for more information.", NAME, matches.free[1]);

View file

@ -66,7 +66,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
println!("{} {}", NAME, VERSION); println!("{} {}", NAME, VERSION);
return 0; return 0;
} }
if matches.opt_present("help") || matches.free.len() > 0 { if matches.opt_present("help") || !matches.free.is_empty() {
println!("{} {}", NAME, VERSION); println!("{} {}", NAME, VERSION);
println!(""); println!("");
println!("Usage:"); println!("Usage:");

View file

@ -74,7 +74,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
return 0; return 0;
} }
let filename = if matches.free.len() > 0 { let filename = if !matches.free.is_empty() {
matches.free[0].as_ref() matches.free[0].as_ref()
} else { } else {
DEFAULT_FILE DEFAULT_FILE
@ -111,7 +111,7 @@ fn exec(filename: &str) {
endutxent(); endutxent();
} }
if users.len() > 0 { if !users.is_empty() {
users.sort(); users.sort();
println!("{}", users.join(" ")); println!("{}", users.join(" "));
} }

View file

@ -109,7 +109,7 @@ extern {
pub fn getgroupcount(name: *const c_char, gid: gid_t) -> int32_t; pub fn getgroupcount(name: *const c_char, gid: gid_t) -> int32_t;
} }
pub fn get_pw_from_args(free: &Vec<String>) -> Option<c_passwd> { pub fn get_pw_from_args(free: &[String]) -> Option<c_passwd> {
if free.len() == 1 { if free.len() == 1 {
let username = &free[0][..]; let username = &free[0][..];
@ -219,7 +219,7 @@ pub fn group(possible_pw: Option<c_passwd>, nflag: bool) {
Err(errno) => Err(errno) =>
crash!(1, "failed to get group list (errno={})", errno), crash!(1, "failed to get group list (errno={})", errno),
Ok(groups) => { Ok(groups) => {
for &g in groups.iter() { for &g in &groups {
if nflag { if nflag {
let group = unsafe { getgrgid(g) }; let group = unsafe { getgrgid(g) };
if !group.is_null() { if !group.is_null() {

View file

@ -82,7 +82,7 @@ pub fn canonicalize<P: AsRef<Path>>(original: P, can_mode: CanonicalizeMode) ->
} }
// Resolve the symlinks where possible // Resolve the symlinks where possible
if parts.len() > 0 { if !parts.is_empty() {
for part in parts[..parts.len()-1].iter() { for part in parts[..parts.len()-1].iter() {
result.push(part); result.push(part);

View file

@ -10,7 +10,7 @@
pub fn from_str(string: &str) -> Result<f64, String> { pub fn from_str(string: &str) -> Result<f64, String> {
let len = string.len(); let len = string.len();
if len == 0 { if len == 0 {
return Err("empty string".to_string()) return Err("empty string".to_owned())
} }
let slice = &string[..len - 1]; let slice = &string[..len - 1];
let (numstr, times) = match string.chars().next_back().unwrap() { let (numstr, times) = match string.chars().next_back().unwrap() {

View file

@ -141,7 +141,7 @@ pub fn signal_by_name_or_value(signal_name_or_value: &str) -> Option<usize> {
if signal_name_or_value == "0" { if signal_name_or_value == "0" {
return Some(0); return Some(0);
} }
for signal in ALL_SIGNALS.iter() { for signal in &ALL_SIGNALS {
let long_name = format!("SIG{}", signal.name); let long_name = format!("SIG{}", signal.name);
if signal.name == signal_name_or_value || (signal_name_or_value == signal.value.to_string()) || (long_name == signal_name_or_value) { if signal.name == signal_name_or_value || (signal_name_or_value == signal.value.to_string()) || (long_name == signal_name_or_value) {
return Some(signal.value); return Some(signal.value);

View file

@ -28,7 +28,7 @@ fn usage(cmap: &UtilityMap) {
println!("Currently defined functions:"); println!("Currently defined functions:");
let mut utils: Vec<&str> = cmap.keys().map(|&s| s).collect(); let mut utils: Vec<&str> = cmap.keys().map(|&s| s).collect();
utils.sort(); utils.sort();
for util in utils.iter() { for util in utils {
println!("\t{}", util); println!("\t{}", util);
} }
} }
@ -83,7 +83,7 @@ fn main() {
let util = &args[1][..]; let util = &args[1][..];
match umap.get(util) { match umap.get(util) {
Some(&uumain) => { Some(&uumain) => {
std::process::exit(uumain(vec![util.to_string(), "--help".to_string()])); std::process::exit(uumain(vec![util.to_owned(), "--help".to_owned()]));
} }
None => { None => {
println!("{}: applet not found", util); println!("{}: applet not found", util);

View file

@ -104,7 +104,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
} }
if matches.free.is_empty() { if matches.free.is_empty() {
matches.free.push("-".to_string()); matches.free.push("-".to_owned());
} }
let settings = Settings::new(&matches); let settings = Settings::new(&matches);
@ -139,7 +139,7 @@ fn wc(files: Vec<String>, settings: &Settings) -> StdResult<(), i32> {
let mut results = vec!(); let mut results = vec!();
let mut max_width: usize = 0; let mut max_width: usize = 0;
for path in files.iter() { for path in &files {
let mut reader = try!(open(&path[..])); let mut reader = try!(open(&path[..]));
let mut line_count: usize = 0; let mut line_count: usize = 0;
@ -153,9 +153,9 @@ fn wc(files: Vec<String>, settings: &Settings) -> StdResult<(), i32> {
// hence the option wrapped in a result here // hence the option wrapped in a result here
while match reader.read_until(LF, &mut raw_line) { while match reader.read_until(LF, &mut raw_line) {
Ok(n) if n > 0 => true, Ok(n) if n > 0 => true,
Err(ref e) if raw_line.len() > 0 => { Err(ref e) if !raw_line.is_empty() => {
show_warning!("Error while reading {}: {}", path, e); show_warning!("Error while reading {}: {}", path, e);
raw_line.len() > 0 !raw_line.is_empty()
}, },
_ => false, _ => false,
} { } {
@ -190,7 +190,7 @@ fn wc(files: Vec<String>, settings: &Settings) -> StdResult<(), i32> {
} }
results.push(Result { results.push(Result {
title: path.to_string(), title: path.clone(),
bytes: byte_count, bytes: byte_count,
chars: char_count, chars: char_count,
lines: line_count, lines: line_count,
@ -211,13 +211,13 @@ fn wc(files: Vec<String>, settings: &Settings) -> StdResult<(), i32> {
max_width = total_byte_count.to_string().len() + 1; max_width = total_byte_count.to_string().len() + 1;
} }
for result in results.iter() { for result in &results {
print_stats(settings, &result, max_width); print_stats(settings, &result, max_width);
} }
if files.len() > 1 { if files.len() > 1 {
let result = Result { let result = Result {
title: "total".to_string(), title: "total".to_owned(),
bytes: total_byte_count, bytes: total_byte_count,
chars: total_char_count, chars: total_char_count,
lines: total_line_count, lines: total_line_count,

View file

@ -47,7 +47,7 @@ pub fn uumain(args: Vec<String>) -> i32 {
return 0; return 0;
} }
let string = if matches.free.is_empty() { let string = if matches.free.is_empty() {
"y".to_string() "y".to_owned()
} else { } else {
matches.free.join(" ") matches.free.join(" ")
}; };