1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-30 20:47:46 +00:00

Update for namespaced enums

This commit is contained in:
Michael Gehring 2014-11-19 21:50:37 +01:00
parent 274b624a34
commit cd409c6d3f
16 changed files with 219 additions and 218 deletions

View file

@ -55,13 +55,13 @@ pub fn uumain(args: Vec<String>) -> int {
let progname = args[0].clone();
let usage = usage("Base64 encode or decode FILE, or standard input, to standard output.", opts);
let mode = if matches.opt_present("help") {
Help
Mode::Help
} else if matches.opt_present("version") {
Version
Mode::Version
} else if matches.opt_present("decode") {
Decode
Mode::Decode
} else {
Encode
Mode::Encode
};
let ignore_garbage = matches.opt_present("ignore-garbage");
let line_wrap = match matches.opt_str("wrap") {
@ -86,10 +86,10 @@ pub fn uumain(args: Vec<String>) -> int {
};
match mode {
Decode => decode(input, ignore_garbage),
Encode => encode(input, line_wrap),
Help => help(progname.as_slice(), usage.as_slice()),
Version => version()
Mode::Decode => decode(input, ignore_garbage),
Mode::Encode => encode(input, line_wrap),
Mode::Help => help(progname.as_slice(), usage.as_slice()),
Mode::Version => version()
}
0

View file

@ -57,12 +57,12 @@ pub fn uumain(args: Vec<String>) -> int {
return 0;
}
let mut number_mode = NumberNone;
let mut number_mode = NumberingMode::NumberNone;
if matches.opt_present("n") {
number_mode = NumberAll;
number_mode = NumberingMode::NumberAll;
}
if matches.opt_present("b") {
number_mode = NumberNonEmpty;
number_mode = NumberingMode::NumberNonEmpty;
}
let show_nonprint = matches.opts_present(["A".to_string(), "e".to_string(),
"t".to_string(), "v".to_string()]);
@ -118,7 +118,7 @@ fn write_lines(files: Vec<String>, number: NumberingMode, squeeze_blank: bool,
};
if in_buf[pos] == '\n' as u8 {
if !at_line_start || !squeeze_blank {
if at_line_start && number == NumberAll {
if at_line_start && number == NumberingMode::NumberAll {
(write!(&mut writer, "{0:6u}\t", line_counter)).unwrap();
line_counter += 1;
}
@ -133,7 +133,7 @@ fn write_lines(files: Vec<String>, number: NumberingMode, squeeze_blank: bool,
at_line_start = true;
continue;
}
if at_line_start && number != NumberNone {
if at_line_start && number != NumberingMode::NumberNone {
(write!(&mut writer, "{0:6u}\t", line_counter)).unwrap();
line_counter += 1;
}
@ -191,7 +191,7 @@ fn write_bytes(files: Vec<String>, number: NumberingMode, squeeze_blank: bool,
}
if byte == '\n' as u8 {
if !at_line_start || !squeeze_blank {
if at_line_start && number == NumberAll {
if at_line_start && number == NumberingMode::NumberAll {
(write!(&mut writer, "{0:6u}\t", line_counter)).unwrap();
line_counter += 1;
}
@ -206,7 +206,7 @@ fn write_bytes(files: Vec<String>, number: NumberingMode, squeeze_blank: bool,
at_line_start = true;
continue;
}
if at_line_start && number != NumberNone {
if at_line_start && number != NumberingMode::NumberNone {
(write!(&mut writer, "{0:6u}\t", line_counter)).unwrap();
line_counter += 1;
at_line_start = false;
@ -267,7 +267,7 @@ fn exec(files: Vec<String>, number: NumberingMode, show_nonprint: bool,
if show_nonprint || show_tabs {
write_bytes(files, number, squeeze_blank, show_ends, show_nonprint, show_tabs);
} else if number != NumberNone || squeeze_blank || show_ends {
} else if number != NumberingMode::NumberNone || squeeze_blank || show_ends {
write_lines(files, number, squeeze_blank, show_ends);
} else {
write_fast(files);

View file

@ -52,8 +52,8 @@ enum LineReader {
impl LineReader {
fn read_line(&mut self) -> IoResult<String> {
match self {
&Stdin(ref mut r) => r.read_line(),
&FileIn(ref mut r) => r.read_line(),
&LineReader::Stdin(ref mut r) => r.read_line(),
&LineReader::FileIn(ref mut r) => r.read_line(),
}
}
}

View file

@ -47,17 +47,17 @@ pub fn uumain(args: Vec<String>) -> int {
let progname = &args[0];
let usage = usage("Copy SOURCE to DEST, or multiple SOURCE(s) to DIRECTORY.", opts);
let mode = if matches.opt_present("version") {
Version
Mode::Version
} else if matches.opt_present("help") {
Help
Mode::Help
} else {
Copy
Mode::Copy
};
match mode {
Copy => copy(matches),
Help => help(progname.as_slice(), usage.as_slice()),
Version => version(),
Mode::Copy => copy(matches),
Mode::Help => help(progname.as_slice(), usage.as_slice()),
Mode::Version => version(),
}
0

View file

@ -99,7 +99,7 @@ impl<R: Reader> Bytes::Select for BufReader<R> {
}
let newline_idx = match self.end - self.start {
0 => return Bytes::EndOfFile,
0 => return Bytes::Selected::EndOfFile,
buf_used if bytes < buf_used => {
// because the output delimiter should only be placed between
// segments check if the byte after bytes is a newline
@ -114,7 +114,7 @@ impl<R: Reader> Bytes::Select for BufReader<R> {
self.start += bytes;
return Bytes::Complete(segment);
return Bytes::Selected::Complete(segment);
}
}
}
@ -129,7 +129,7 @@ impl<R: Reader> Bytes::Select for BufReader<R> {
self.start = 0;
self.end = 0;
return Bytes::Partial(segment);
return Bytes::Selected::Partial(segment);
}
}
}
@ -139,6 +139,6 @@ impl<R: Reader> Bytes::Select for BufReader<R> {
let segment = self.buffer.slice(self.start, new_start);
self.start = new_start;
Bytes::NewlineFound(segment)
Bytes::Selected::NewlineFound(segment)
}
}

View file

@ -55,7 +55,8 @@ fn list_to_ranges(list: &str, complement: bool) -> Result<Vec<Range>, String> {
fn cut_bytes<R: Reader>(reader: R,
ranges: &Vec<Range>,
opts: &Options) -> int {
use buffer::Bytes::{Select, NewlineFound, Complete, Partial, EndOfFile};
use buffer::Bytes::Select;
use buffer::Bytes::Selected::{NewlineFound, Complete, Partial, EndOfFile};
let mut buf_read = buffer::BufReader::new(reader);
let mut out = BufferedWriter::new(stdio::stdout_raw());
@ -404,13 +405,13 @@ fn cut_files(mut filenames: Vec<String>, mode: Mode) -> int {
if stdin_read { continue }
exit_code |= match mode {
Bytes(ref ranges, ref opts) => {
Mode::Bytes(ref ranges, ref opts) => {
cut_bytes(stdio::stdin_raw(), ranges, opts)
}
Characters(ref ranges, ref opts) => {
Mode::Characters(ref ranges, ref opts) => {
cut_characters(stdio::stdin_raw(), ranges, opts)
}
Fields(ref ranges, ref opts) => {
Mode::Fields(ref ranges, ref opts) => {
cut_fields(stdio::stdin_raw(), ranges, opts)
}
};
@ -433,11 +434,11 @@ fn cut_files(mut filenames: Vec<String>, mode: Mode) -> int {
};
exit_code |= match mode {
Bytes(ref ranges, ref opts) => cut_bytes(file, ranges, opts),
Characters(ref ranges, ref opts) => {
Mode::Bytes(ref ranges, ref opts) => cut_bytes(file, ranges, opts),
Mode::Characters(ref ranges, ref opts) => {
cut_characters(file, ranges, opts)
}
Fields(ref ranges, ref opts) => cut_fields(file, ranges, opts)
Mode::Fields(ref ranges, ref opts) => cut_fields(file, ranges, opts)
};
}
}
@ -499,13 +500,13 @@ pub fn uumain(args: Vec<String>) -> int {
matches.opt_str("fields")) {
(Some(byte_ranges), None, None) => {
list_to_ranges(byte_ranges.as_slice(), complement).map(|ranges|
Bytes(ranges,
Mode::Bytes(ranges,
Options { out_delim: matches.opt_str("output-delimiter") })
)
}
(None, Some(char_ranges), None) => {
list_to_ranges(char_ranges.as_slice(), complement).map(|ranges|
Characters(ranges,
Mode::Characters(ranges,
Options { out_delim: matches.opt_str("output-delimiter") })
)
}
@ -520,7 +521,7 @@ pub fn uumain(args: Vec<String>) -> int {
if delim.as_slice().char_len() != 1 {
Err("the delimiter must be a single character".to_string())
} else {
Ok(Fields(ranges,
Ok(Mode::Fields(ranges,
FieldOptions {
delimiter: delim,
out_delimeter: out_delim,
@ -528,7 +529,7 @@ pub fn uumain(args: Vec<String>) -> int {
}))
}
}
None => Ok(Fields(ranges,
None => Ok(Mode::Fields(ranges,
FieldOptions {
delimiter: "\t".to_string(),
out_delimeter: out_delim,

View file

@ -40,16 +40,16 @@ impl Line {
// when we know that it's a FormatLine, as in the ParagraphStream iterator
fn get_formatline(self) -> FileLine {
match self {
FormatLine(fl) => fl,
NoFormatLine(..) => panic!("Found NoFormatLine when expecting FormatLine")
Line::FormatLine(fl) => fl,
Line::NoFormatLine(..) => panic!("Found NoFormatLine when expecting FormatLine")
}
}
// when we know that it's a NoFormatLine, as in the ParagraphStream iterator
fn get_noformatline(self) -> (String, bool) {
match self {
NoFormatLine(s, b) => (s, b),
FormatLine(..) => panic!("Found FormatLine when expecting NoFormatLine")
Line::NoFormatLine(s, b) => (s, b),
Line::FormatLine(..) => panic!("Found FormatLine when expecting NoFormatLine")
}
}
}
@ -154,34 +154,34 @@ impl<'a> Iterator<Line> for FileLines<'a> {
// Err(true) indicates that this was a linebreak,
// which is important to know when detecting mail headers
if n.as_slice().is_whitespace() {
return Some(NoFormatLine("\n".to_string(), true));
return Some(Line::NoFormatLine("\n".to_string(), true));
}
// if this line does not match the prefix,
// emit the line unprocessed and iterate again
let (pmatch, poffset) = self.match_prefix(n.as_slice());
if !pmatch {
return Some(NoFormatLine(n, false));
return Some(Line::NoFormatLine(n, false));
} else if n.as_slice().slice_from(poffset + self.opts.prefix.len()).is_whitespace() {
// if the line matches the prefix, but is blank after,
// don't allow lines to be combined through it (that is,
// treat it like a blank line, except that since it's
// not truly blank we will not allow mail headers on the
// following line)
return Some(NoFormatLine(n, false));
return Some(Line::NoFormatLine(n, false));
}
// skip if this line matches the anti_prefix
// (NOTE definition of match_anti_prefix is TRUE if we should process)
if !self.match_anti_prefix(n.as_slice()) {
return Some(NoFormatLine(n, false));
return Some(Line::NoFormatLine(n, false));
}
// figure out the indent, prefix, and prefixindent ending points
let prefix_end = poffset + self.opts.prefix.len();
let (indent_end, prefix_len, indent_len) = self.compute_indent(n.as_slice(), prefix_end);
Some(FormatLine(FileLine {
Some(Line::FormatLine(FileLine {
line : n,
indent_end : indent_end,
pfxind_end : poffset,
@ -259,8 +259,8 @@ impl<'a> Iterator<Result<Paragraph, String>> for ParagraphStream<'a> {
match self.lines.peek() {
None => return None,
Some(l) => match l {
&FormatLine(_) => false,
&NoFormatLine(_, _) => true
&Line::FormatLine(_) => false,
&Line::NoFormatLine(_, _) => true
}
};
@ -292,8 +292,8 @@ impl<'a> Iterator<Result<Paragraph, String>> for ParagraphStream<'a> {
None => break,
Some(l) => {
match l {
&FormatLine(ref x) => x,
&NoFormatLine(..) => break
&Line::FormatLine(ref x) => x,
&Line::NoFormatLine(..) => break
}
}
};

View file

@ -66,17 +66,17 @@ pub fn uumain(args: Vec<String>) -> int {
};
let mode = if matches.opt_present("version") {
Version
Mode::Version
} else if matches.opt_present("help") {
Help
Mode::Help
} else {
HostId
Mode::HostId
};
match mode {
HostId => hostid(),
Help => help(NAME, usage.as_slice()),
Version => version(),
Mode::HostId => hostid(),
Mode::Help => help(NAME, usage.as_slice()),
Mode::Version => version(),
}
0

View file

@ -74,23 +74,23 @@ pub fn uumain(args: Vec<String>) -> int {
};
let mode = if matches.opt_present("version") {
Version
Mode::Version
} else if matches.opt_present("help") {
Help
Mode::Help
} else if matches.opt_present("table") {
Table
Mode::Table
} else if matches.opt_present("list") {
List
Mode::List
} else {
Kill
Mode::Kill
};
match mode {
Kill => return kill(matches.opt_str("signal").unwrap_or(obs_signal.unwrap_or("9".to_string())).as_slice(), matches.free),
Table => table(),
List => list(matches.opt_str("list")),
Help => help(NAME, usage.as_slice()),
Version => version(),
Mode::Kill => return kill(matches.opt_str("signal").unwrap_or(obs_signal.unwrap_or("9".to_string())).as_slice(), matches.free),
Mode::Table => table(),
Mode::List => list(matches.opt_str("list")),
Mode::Help => help(NAME, usage.as_slice()),
Mode::Version => version(),
}
0

View file

@ -94,23 +94,23 @@ pub fn uumain(args: Vec<String>) -> int {
* To default to no-clobber in that situation seems safer:
*/
let overwrite_mode = if matches.opt_present("no-clobber") {
NoClobber
OverwriteMode::NoClobber
} else if matches.opt_present("interactive") {
Interactive
OverwriteMode::Interactive
} else {
Force
OverwriteMode::Force
};
let backup_mode = if matches.opt_present("b") {
SimpleBackup
BackupMode::SimpleBackup
} else if matches.opt_present("backup") {
match matches.opt_str("backup") {
None => SimpleBackup,
None => BackupMode::SimpleBackup,
Some(mode) => match mode.as_slice() {
"simple" | "never" => SimpleBackup,
"numbered" | "t" => NumberedBackup,
"existing" | "nil" => ExistingBackup,
"none" | "off" => NoBackup,
"simple" | "never" => BackupMode::SimpleBackup,
"numbered" | "t" => BackupMode::NumberedBackup,
"existing" | "nil" => BackupMode::ExistingBackup,
"none" | "off" => BackupMode::NoBackup,
x => {
show_error!("invalid argument {} for backup type\n\
Try 'mv --help' for more information.", x);
@ -119,10 +119,10 @@ pub fn uumain(args: Vec<String>) -> int {
}
}
} else {
NoBackup
BackupMode::NoBackup
};
if overwrite_mode == NoClobber && backup_mode != NoBackup {
if overwrite_mode == OverwriteMode::NoClobber && backup_mode != BackupMode::NoBackup {
show_error!("options --backup and --no-clobber are mutually exclusive\n\
Try 'mv --help' for more information.");
return 1;
@ -276,21 +276,21 @@ fn rename(from: &Path, to: &Path, b: &Behaviour) -> IoResult<()> {
if to.exists() {
match b.overwrite {
NoClobber => return Ok(()),
Interactive => {
OverwriteMode::NoClobber => return Ok(()),
OverwriteMode::Interactive => {
print!("{}: overwrite {}? ", NAME, to.display());
if !read_yes() {
return Ok(());
}
},
Force => {}
OverwriteMode::Force => {}
};
backup_path = match b.backup {
NoBackup => None,
SimpleBackup => Some(simple_backup_path(to, &b.suffix)),
NumberedBackup => Some(numbered_backup_path(to)),
ExistingBackup => Some(existing_backup_path(to, &b.suffix))
BackupMode::NoBackup => None,
BackupMode::SimpleBackup => Some(simple_backup_path(to, &b.suffix)),
BackupMode::NumberedBackup => Some(numbered_backup_path(to)),
BackupMode::ExistingBackup => Some(existing_backup_path(to, &b.suffix))
};
if let Some(ref p) = backup_path {
try!(fs::rename(to, p));

View file

@ -4,12 +4,12 @@ extern crate regex;
// parse_style parses a style string into a NumberingStyle.
fn parse_style(chars: &[char]) -> Result<::NumberingStyle, String> {
match chars {
['a'] => { Ok(::NumberForAll) },
['t'] => { Ok(::NumberForNonEmpty) },
['n'] => { Ok(::NumberForNone) },
['a'] => { Ok(::NumberingStyle::NumberForAll) },
['t'] => { Ok(::NumberingStyle::NumberForNonEmpty) },
['n'] => { Ok(::NumberingStyle::NumberForNone) },
['p', rest..] => {
match regex::Regex::new(String::from_chars(rest).as_slice()) {
Ok(re) => Ok(::NumberForRegularExpression(re)),
Ok(re) => Ok(::NumberingStyle::NumberForRegularExpression(re)),
Err(_) => Err(String::from_str("Illegal regular expression")),
}
}
@ -32,9 +32,9 @@ pub fn parse_options(settings: &mut ::Settings, opts: &getopts::Matches) -> Vec<
match opts.opt_str("n") {
None => {},
Some(val) => match val.as_slice() {
"ln" => { settings.number_format = ::Left; },
"rn" => { settings.number_format = ::Right; },
"rz" => { settings.number_format = ::RightZero; },
"ln" => { settings.number_format = ::NumberFormat::Left; },
"rn" => { settings.number_format = ::NumberFormat::Right; },
"rz" => { settings.number_format = ::NumberFormat::RightZero; },
_ => { errs.push(String::from_str("Illegal value for -n")); },
}
}

View file

@ -93,15 +93,15 @@ pub fn uumain(args: Vec<String>) -> int {
// A mutable settings object, initialized with the defaults.
let mut settings = Settings {
header_numbering: NumberForNone,
body_numbering: NumberForAll,
footer_numbering: NumberForNone,
header_numbering: NumberingStyle::NumberForNone,
body_numbering: NumberingStyle::NumberForAll,
footer_numbering: NumberingStyle::NumberForNone,
section_delimiter: ['\\', ':'],
starting_line_number: 1,
line_increment: 1,
join_blank_lines: 1,
number_width: 6,
number_format: Right,
number_format: NumberFormat::Right,
renumber: true,
number_separator: String::from_str("\t"),
};
@ -167,12 +167,12 @@ fn nl<T: Reader> (reader: &mut BufferedReader<T>, settings: &Settings) {
let mut line_no_threshold = std::num::pow(10u64, line_no_width);
let mut empty_line_count: u64 = 0;
let fill_char = match settings.number_format {
RightZero => '0',
NumberFormat::RightZero => '0',
_ => ' '
};
// Initially, we use the body's line counting settings
let mut regex_filter = match settings.body_numbering {
NumberForRegularExpression(ref re) => re,
NumberingStyle::NumberForRegularExpression(ref re) => re,
_ => REGEX_DUMMY,
};
let mut line_filter = pass_regex;
@ -239,16 +239,16 @@ fn nl<T: Reader> (reader: &mut BufferedReader<T>, settings: &Settings) {
&settings.body_numbering
}
} {
NumberForAll => {
NumberingStyle::NumberForAll => {
line_filter = pass_all;
},
NumberForNonEmpty => {
NumberingStyle::NumberForNonEmpty => {
line_filter = pass_nonempty;
},
NumberForNone => {
NumberingStyle::NumberForNone => {
line_filter = pass_none;
}
NumberForRegularExpression(ref re) => {
NumberingStyle::NumberForRegularExpression(ref re) => {
line_filter = pass_regex;
regex_filter = re;
}
@ -285,7 +285,7 @@ fn nl<T: Reader> (reader: &mut BufferedReader<T>, settings: &Settings) {
}
let fill = String::from_char(w, fill_char);
match settings.number_format {
Left => {
NumberFormat::Left => {
println!("{1}{0}{2}{3}", fill, line_no, settings.number_separator, line)
},
_ => {

View file

@ -83,27 +83,27 @@ pub fn uumain(args: Vec<String>) -> int {
let force = matches.opt_present("force");
let interactive =
if matches.opt_present("i") {
InteractiveAlways
InteractiveMode::InteractiveAlways
} else if matches.opt_present("I") {
InteractiveOnce
InteractiveMode::InteractiveOnce
} else if matches.opt_present("interactive") {
match matches.opt_str("interactive").unwrap().as_slice() {
"none" => InteractiveNone,
"once" => InteractiveOnce,
"always" => InteractiveAlways,
"none" => InteractiveMode::InteractiveNone,
"once" => InteractiveMode::InteractiveOnce,
"always" => InteractiveMode::InteractiveAlways,
val => {
crash!(1, "Invalid argument to interactive ({})", val)
}
}
} else {
InteractiveNone
InteractiveMode::InteractiveNone
};
let one_fs = matches.opt_present("one-file-system");
let preserve_root = !matches.opt_present("no-preserve-root");
let recursive = matches.opt_present("recursive");
let dir = matches.opt_present("dir");
let verbose = matches.opt_present("verbose");
if interactive == InteractiveOnce && (recursive || matches.free.len() > 3) {
if interactive == InteractiveMode::InteractiveOnce && (recursive || matches.free.len() > 3) {
let msg =
if recursive {
"Remove all arguments recursively? "
@ -169,7 +169,7 @@ fn remove(files: Vec<String>, force: bool, interactive: InteractiveMode, one_fs:
fn remove_dir(path: &Path, name: &str, interactive: InteractiveMode, verbose: bool) -> Result<(), int> {
let response =
if interactive == InteractiveAlways {
if interactive == InteractiveMode::InteractiveAlways {
prompt_file(path, name)
} else {
true
@ -189,7 +189,7 @@ fn remove_dir(path: &Path, name: &str, interactive: InteractiveMode, verbose: bo
fn remove_file(path: &Path, name: &str, interactive: InteractiveMode, verbose: bool) -> Result<(), int> {
let response =
if interactive == InteractiveAlways {
if interactive == InteractiveMode::InteractiveAlways {
prompt_file(path, name)
} else {
true

View file

@ -76,7 +76,7 @@ With no FILE, or when FILE is -, read standard input.",
return 1;
}
match parse_range(range) {
Ok(m) => InputRange(m),
Ok(m) => Mode::InputRange(m),
Err((msg, code)) => {
show_error!("{}", msg);
return code;
@ -85,12 +85,12 @@ With no FILE, or when FILE is -, read standard input.",
}
None => {
if echo {
Echo
Mode::Echo
} else {
if matches.free.len() == 0 {
matches.free.push("-".to_string());
}
Default
Mode::Default
}
}
};
@ -122,9 +122,9 @@ With no FILE, or when FILE is -, read standard input.",
fn shuf(input: Vec<String>, mode: Mode, repeat: bool, zero: bool, count: uint, output: Option<String>, random: Option<String>) -> IoResult<()> {
match mode {
Echo => shuf_lines(input, repeat, zero, count, output, random),
InputRange(range) => shuf_lines(range.map(|num| num.to_string()).collect(), repeat, zero, count, output, random),
Default => {
Mode::Echo => shuf_lines(input, repeat, zero, count, output, random),
Mode::InputRange(range) => shuf_lines(range.map(|num| num.to_string()).collect(), repeat, zero, count, output, random),
Mode::Default => {
let lines: Vec<String> = input.into_iter().flat_map(|filename| {
let slice = filename.as_slice();
let mut file_buf;
@ -159,8 +159,8 @@ enum WrappedRng {
impl WrappedRng {
fn next_u32(&mut self) -> u32 {
match self {
&RngFile(ref mut r) => r.next_u32(),
&RngDefault(ref mut r) => r.next_u32(),
&WrappedRng::RngFile(ref mut r) => r.next_u32(),
&WrappedRng::RngDefault(ref mut r) => r.next_u32(),
}
}
}
@ -171,8 +171,8 @@ fn shuf_lines(mut lines: Vec<String>, repeat: bool, zero: bool, count: uint, out
None => box io::stdout() as Box<Writer>
};
let mut rng = match random {
Some(name) => RngFile(rand::reader::ReaderRng::new(try!(io::File::open(&Path::new(name))))),
None => RngDefault(rand::task_rng()),
Some(name) => WrappedRng::RngFile(rand::reader::ReaderRng::new(try!(io::File::open(&Path::new(name))))),
None => WrappedRng::RngDefault(rand::task_rng()),
};
let mut len = lines.len();
let max = if repeat { count } else { cmp::min(count, len) };

View file

@ -53,23 +53,23 @@ fn one(args: &[&[u8]]) -> bool {
fn two(args: &[&[u8]], error: &mut bool) -> bool {
match args[0] {
b"!" => !one(args.slice_from(1)),
b"-b" => path(args[1], BlockSpecial),
b"-c" => path(args[1], CharacterSpecial),
b"-d" => path(args[1], Directory),
b"-e" => path(args[1], Exists),
b"-f" => path(args[1], Regular),
b"-g" => path(args[1], GroupIDFlag),
b"-h" => path(args[1], SymLink),
b"-L" => path(args[1], SymLink),
b"-b" => path(args[1], PathCondition::BlockSpecial),
b"-c" => path(args[1], PathCondition::CharacterSpecial),
b"-d" => path(args[1], PathCondition::Directory),
b"-e" => path(args[1], PathCondition::Exists),
b"-f" => path(args[1], PathCondition::Regular),
b"-g" => path(args[1], PathCondition::GroupIDFlag),
b"-h" => path(args[1], PathCondition::SymLink),
b"-L" => path(args[1], PathCondition::SymLink),
b"-n" => one(args.slice_from(1)),
b"-p" => path(args[1], FIFO),
b"-r" => path(args[1], Readable),
b"-S" => path(args[1], Socket),
b"-s" => path(args[1], NonEmpty),
b"-p" => path(args[1], PathCondition::FIFO),
b"-r" => path(args[1], PathCondition::Readable),
b"-S" => path(args[1], PathCondition::Socket),
b"-s" => path(args[1], PathCondition::NonEmpty),
b"-t" => isatty(args[1]),
b"-u" => path(args[1], UserIDFlag),
b"-w" => path(args[1], Writable),
b"-x" => path(args[1], Executable),
b"-u" => path(args[1], PathCondition::UserIDFlag),
b"-w" => path(args[1], PathCondition::Writable),
b"-x" => path(args[1], PathCondition::Executable),
b"-z" => !one(args.slice_from(1)),
_ => {
*error = true;
@ -82,12 +82,12 @@ fn three(args: &[&[u8]], error: &mut bool) -> bool {
match args[1] {
b"=" => args[0] == args[2],
b"!=" => args[0] != args[2],
b"-eq" => integers(args[0], args[2], Equal),
b"-ne" => integers(args[0], args[2], Unequal),
b"-gt" => integers(args[0], args[2], Greater),
b"-ge" => integers(args[0], args[2], GreaterEqual),
b"-lt" => integers(args[0], args[2], Less),
b"-le" => integers(args[0], args[2], LessEqual),
b"-eq" => integers(args[0], args[2], IntegerCondition::Equal),
b"-ne" => integers(args[0], args[2], IntegerCondition::Unequal),
b"-gt" => integers(args[0], args[2], IntegerCondition::Greater),
b"-ge" => integers(args[0], args[2], IntegerCondition::GreaterEqual),
b"-lt" => integers(args[0], args[2], IntegerCondition::Less),
b"-le" => integers(args[0], args[2], IntegerCondition::LessEqual),
_ => match args[0] {
b"!" => !two(args.slice_from(1), error),
_ => {
@ -129,12 +129,12 @@ fn integers(a: &[u8], b: &[u8], cond: IntegerCondition) -> bool {
_ => return false,
};
match cond {
Equal => a == b,
Unequal => a != b,
Greater => a > b,
GreaterEqual => a >= b,
Less => a < b,
LessEqual => a <= b,
IntegerCondition::Equal => a == b,
IntegerCondition::Unequal => a != b,
IntegerCondition::Greater => a > b,
IntegerCondition::GreaterEqual => a >= b,
IntegerCondition::Less => a < b,
IntegerCondition::LessEqual => a <= b,
}
}
@ -207,7 +207,7 @@ fn parse_expr(mut args: &[&[u8]], error: &mut bool) -> bool {
let lhs = dispatch(&mut args, error);
if args.len() > 0 {
parse_expr_helper(&hashmap, &mut args, lhs, Unknown, error)
parse_expr_helper(&hashmap, &mut args, lhs, Precedence::Unknown, error)
} else {
lhs
}
@ -238,14 +238,14 @@ fn parse_expr_helper<'a>(hashmap: &HashMap<&'a [u8], Precedence>,
rhs = parse_expr_helper(hashmap, args, rhs, subprec, error);
}
lhs = match prec {
UnOp | BUnOp => {
Precedence::UnOp | Precedence::BUnOp => {
*error = true;
false
}
And => lhs && rhs,
Or => lhs || rhs,
BinOp => three(&[if lhs { b" " } else { b"" }, op, if rhs { b" " } else { b"" }], error),
Paren => unimplemented!(), // TODO: implement parentheses
Precedence::And => lhs && rhs,
Precedence::Or => lhs || rhs,
Precedence::BinOp => three(&[if lhs { b" " } else { b"" }, op, if rhs { b" " } else { b"" }], error),
Precedence::Paren => unimplemented!(), // TODO: implement parentheses
_ => unreachable!()
};
if args.len() > 0 {
@ -262,41 +262,41 @@ fn parse_expr_helper<'a>(hashmap: &HashMap<&'a [u8], Precedence>,
fn setup_hashmap<'a>() -> HashMap<&'a [u8], Precedence> {
let mut hashmap = HashMap::<&'a [u8], Precedence>::new();
hashmap.insert(b"-b", UnOp);
hashmap.insert(b"-c", UnOp);
hashmap.insert(b"-d", UnOp);
hashmap.insert(b"-e", UnOp);
hashmap.insert(b"-f", UnOp);
hashmap.insert(b"-g", UnOp);
hashmap.insert(b"-h", UnOp);
hashmap.insert(b"-L", UnOp);
hashmap.insert(b"-n", UnOp);
hashmap.insert(b"-p", UnOp);
hashmap.insert(b"-r", UnOp);
hashmap.insert(b"-S", UnOp);
hashmap.insert(b"-s", UnOp);
hashmap.insert(b"-t", UnOp);
hashmap.insert(b"-u", UnOp);
hashmap.insert(b"-w", UnOp);
hashmap.insert(b"-x", UnOp);
hashmap.insert(b"-z", UnOp);
hashmap.insert(b"-b", Precedence::UnOp);
hashmap.insert(b"-c", Precedence::UnOp);
hashmap.insert(b"-d", Precedence::UnOp);
hashmap.insert(b"-e", Precedence::UnOp);
hashmap.insert(b"-f", Precedence::UnOp);
hashmap.insert(b"-g", Precedence::UnOp);
hashmap.insert(b"-h", Precedence::UnOp);
hashmap.insert(b"-L", Precedence::UnOp);
hashmap.insert(b"-n", Precedence::UnOp);
hashmap.insert(b"-p", Precedence::UnOp);
hashmap.insert(b"-r", Precedence::UnOp);
hashmap.insert(b"-S", Precedence::UnOp);
hashmap.insert(b"-s", Precedence::UnOp);
hashmap.insert(b"-t", Precedence::UnOp);
hashmap.insert(b"-u", Precedence::UnOp);
hashmap.insert(b"-w", Precedence::UnOp);
hashmap.insert(b"-x", Precedence::UnOp);
hashmap.insert(b"-z", Precedence::UnOp);
hashmap.insert(b"=", BinOp);
hashmap.insert(b"!=", BinOp);
hashmap.insert(b"-eq", BinOp);
hashmap.insert(b"-ne", BinOp);
hashmap.insert(b"-gt", BinOp);
hashmap.insert(b"-ge", BinOp);
hashmap.insert(b"-lt", BinOp);
hashmap.insert(b"-le", BinOp);
hashmap.insert(b"=", Precedence::BinOp);
hashmap.insert(b"!=", Precedence::BinOp);
hashmap.insert(b"-eq", Precedence::BinOp);
hashmap.insert(b"-ne", Precedence::BinOp);
hashmap.insert(b"-gt", Precedence::BinOp);
hashmap.insert(b"-ge", Precedence::BinOp);
hashmap.insert(b"-lt", Precedence::BinOp);
hashmap.insert(b"-le", Precedence::BinOp);
hashmap.insert(b"!", BUnOp);
hashmap.insert(b"!", Precedence::BUnOp);
hashmap.insert(b"-a", And);
hashmap.insert(b"-o", Or);
hashmap.insert(b"-a", Precedence::And);
hashmap.insert(b"-o", Precedence::Or);
hashmap.insert(b"(", Paren);
hashmap.insert(b")", Paren);
hashmap.insert(b"(", Precedence::Paren);
hashmap.insert(b")", Precedence::Paren);
hashmap
}
@ -346,7 +346,7 @@ fn path(path: &[u8], cond: PathCondition) -> bool {
let path = unsafe { path.to_c_str_unchecked() };
let mut stat = unsafe { std::mem::zeroed() };
if cond == SymLink {
if cond == PathCondition::SymLink {
if unsafe { lstat(path.as_ptr(), &mut stat) } == 0 {
if stat.st_mode & S_IFMT == S_IFLNK {
return true;
@ -359,20 +359,20 @@ fn path(path: &[u8], cond: PathCondition) -> bool {
}
let file_type = stat.st_mode & S_IFMT;
match cond {
BlockSpecial => file_type == S_IFBLK,
CharacterSpecial => file_type == S_IFCHR,
Directory => file_type == S_IFDIR,
Exists => true,
Regular => file_type == S_IFREG,
GroupIDFlag => stat.st_mode & S_ISGID != 0,
SymLink => true,
FIFO => file_type == S_IFIFO,
Readable => perm(stat, Read),
Socket => file_type == S_IFSOCK,
NonEmpty => stat.st_size > 0,
UserIDFlag => stat.st_mode & S_ISUID != 0,
Writable => perm(stat, Write),
Executable => perm(stat, Execute),
PathCondition::BlockSpecial => file_type == S_IFBLK,
PathCondition::CharacterSpecial => file_type == S_IFCHR,
PathCondition::Directory => file_type == S_IFDIR,
PathCondition::Exists => true,
PathCondition::Regular => file_type == S_IFREG,
PathCondition::GroupIDFlag => stat.st_mode & S_ISGID != 0,
PathCondition::SymLink => true,
PathCondition::FIFO => file_type == S_IFIFO,
PathCondition::Readable => perm(stat, Permission::Read),
PathCondition::Socket => file_type == S_IFSOCK,
PathCondition::NonEmpty => stat.st_size > 0,
PathCondition::UserIDFlag => stat.st_mode & S_ISUID != 0,
PathCondition::Writable => perm(stat, Permission::Write),
PathCondition::Executable => perm(stat, Permission::Execute),
}
}

View file

@ -109,7 +109,7 @@ fn truncate(no_create: bool, _: bool, reference: Option<String>, size: Option<St
}
};
match fs::stat(rfile.path()) {
Ok(stat) => (stat.size, Reference),
Ok(stat) => (stat.size, TruncateMode::Reference),
Err(f) => {
show_error!("{}", f.to_string());
return Err(1);
@ -132,13 +132,13 @@ fn truncate(no_create: bool, _: bool, reference: Option<String>, size: Option<St
}
};
let tsize = match mode {
Reference => refsize,
Extend => fsize + refsize,
Reduce => fsize - refsize,
AtMost => if fsize > refsize { refsize } else { fsize },
AtLeast => if fsize < refsize { refsize } else { fsize },
RoundDown => fsize - fsize % refsize,
RoundUp => fsize + fsize % refsize
TruncateMode::Reference => refsize,
TruncateMode::Extend => fsize + refsize,
TruncateMode::Reduce => fsize - refsize,
TruncateMode::AtMost => if fsize > refsize { refsize } else { fsize },
TruncateMode::AtLeast => if fsize < refsize { refsize } else { fsize },
TruncateMode::RoundDown => fsize - fsize % refsize,
TruncateMode::RoundUp => fsize + fsize % refsize
};
match file.truncate(tsize as i64) {
Ok(_) => {}
@ -160,17 +160,17 @@ fn truncate(no_create: bool, _: bool, reference: Option<String>, size: Option<St
fn parse_size(size: &str) -> (u64, TruncateMode) {
let mode = match size.char_at(0) {
'+' => Extend,
'-' => Reduce,
'<' => AtMost,
'>' => AtLeast,
'/' => RoundDown,
'*' => RoundUp,
_ => Reference /* assume that the size is just a number */
'+' => TruncateMode::Extend,
'-' => TruncateMode::Reduce,
'<' => TruncateMode::AtMost,
'>' => TruncateMode::AtLeast,
'/' => TruncateMode::RoundDown,
'*' => TruncateMode::RoundUp,
_ => TruncateMode::Reference /* assume that the size is just a number */
};
let bytes = {
let mut slice =
if mode == Reference {
if mode == TruncateMode::Reference {
let size: &str = size;
size
} else {