1
Fork 0
mirror of https://github.com/RGBCube/uutils-coreutils synced 2025-07-28 11:37:44 +00:00

Fix everything but md5sum (blocked on rust-crypto) for latest Rust

This commit is contained in:
Arcterus 2014-04-25 22:03:08 -07:00
parent eb57470453
commit 4e8703e04f
24 changed files with 176 additions and 181 deletions

View file

@ -6,7 +6,7 @@ fn test_output_multi_files_print_all_chars() {
let prog = Process::output("build/cat",
[~"cat/fixtures/alpha.txt", ~"cat/fixtures/256.txt",
~"-A", ~"-n"]).unwrap();
let out = str::from_utf8_owned(prog.output).unwrap();
let out = str::from_utf8_owned(prog.output.as_slice().to_owned()).unwrap();
assert_eq!(out,
~" 1\tabcde$\n 2\tfghij$\n 3\tklmno$\n 4\tpqrst$\n 5\tuvwxyz$\n 6\t^@^A^B^C^D^E^F^G^H^I$\n 7\t^K^L^M^N^O^P^Q^R^S^T^U^V^W^X^Y^Z^[^\\^]^^^_ !\"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~^?M-^@M-^AM-^BM-^CM-^DM-^EM-^FM-^GM-^HM-^IM-^JM-^KM-^LM-^MM-^NM-^OM-^PM-^QM-^RM-^SM-^TM-^UM-^VM-^WM-^XM-^YM-^ZM-^[M-^\\M-^]M-^^M-^_M- M-!M-\"M-#M-$M-%M-&M-\'M-(M-)M-*M-+M-,M--M-.M-/M-0M-1M-2M-3M-4M-5M-6M-7M-8M-9M-:M-;M-<M-=M->M-?M-@M-AM-BM-CM-DM-EM-FM-GM-HM-IM-JM-KM-LM-MM-NM-OM-PM-QM-RM-SM-TM-UM-VM-WM-XM-YM-ZM-[M-\\M-]M-^M-_M-`M-aM-bM-cM-dM-eM-fM-gM-hM-iM-jM-kM-lM-mM-nM-oM-pM-qM-rM-sM-tM-uM-vM-wM-xM-yM-zM-{M-|M-}M-~M-^?");
}
@ -17,7 +17,7 @@ fn test_stdin_squeeze() {
prog.stdin.take_unwrap().write(bytes!("\x00\x01\x02"));
let out = str::from_utf8_owned(prog.wait_with_output().output).unwrap();
let out = str::from_utf8_owned(prog.wait_with_output().output.as_slice().to_owned()).unwrap();
assert_eq!(out, ~"^@^A^B");
}
@ -27,6 +27,6 @@ fn test_stdin_number_non_blank() {
prog.stdin.take_unwrap().write(bytes!("\na\nb\n\n\nc"));
let out = str::from_utf8_owned(prog.wait_with_output().output).unwrap();
let out = str::from_utf8_owned(prog.wait_with_output().output.as_slice().to_owned()).unwrap();
assert_eq!(out, ~"\n 1\ta\n 2\tb\n\n\n 3\tc");
}

View file

@ -1,14 +1,14 @@
#![allow(dead_code, non_camel_case_types)]
extern crate getopts;
extern crate libc;
use libc::{
use self::libc::{
c_char,
c_int,
uid_t,
time_t,
getgroups
time_t
};
use self::libc::funcs::posix88::unistd::getgroups;
use std::vec::Vec;
@ -16,16 +16,16 @@ use std::ptr::read;
use std::str::raw::from_c_str;
pub struct c_passwd {
pw_name: *c_char, /* user name */
pw_passwd: *c_char, /* user name */
pw_uid: c_int, /* user uid */
pw_gid: c_int, /* user gid */
pw_change: time_t,
pw_class: *c_char,
pw_gecos: *c_char,
pw_dir: *c_char,
pw_shell: *c_char,
pw_expire: time_t
pub pw_name: *c_char, /* user name */
pub pw_passwd: *c_char, /* user name */
pub pw_uid: c_int, /* user uid */
pub pw_gid: c_int, /* user gid */
pub pw_change: time_t,
pub pw_class: *c_char,
pub pw_gecos: *c_char,
pub pw_dir: *c_char,
pub pw_shell: *c_char,
pub pw_expire: time_t
}
#[cfg(target_os = "macos")]
@ -48,19 +48,19 @@ pub struct utsname {
}
pub struct c_group {
gr_name: *c_char /* group name */
pub gr_name: *c_char /* group name */
}
pub struct c_tm {
tm_sec: c_int, /* seconds */
tm_min: c_int, /* minutes */
tm_hour: c_int, /* hours */
tm_mday: c_int, /* day of the month */
tm_mon: c_int, /* month */
tm_year: c_int, /* year */
tm_wday: c_int, /* day of the week */
tm_yday: c_int, /* day in the year */
tm_isdst: c_int /* daylight saving time */
pub tm_sec: c_int, /* seconds */
pub tm_min: c_int, /* minutes */
pub tm_hour: c_int, /* hours */
pub tm_mday: c_int, /* day of the month */
pub tm_mon: c_int, /* month */
pub tm_year: c_int, /* year */
pub tm_wday: c_int, /* day of the week */
pub tm_yday: c_int, /* day in the year */
pub tm_isdst: c_int /* daylight saving time */
}
extern {

View file

@ -9,6 +9,8 @@
#![macro_escape]
extern crate libc;
#[macro_export]
macro_rules! show_error(
($exitcode:expr, $($args:expr),+) => ({
@ -30,7 +32,7 @@ macro_rules! show_warning(
macro_rules! crash(
($exitcode:expr, $($args:expr),+) => ({
show_error!($exitcode, $($args),+);
unsafe { ::libc::exit($exitcode as ::libc::c_int); }
unsafe { self::libc::exit($exitcode as self::libc::c_int); }
})
)
@ -38,7 +40,7 @@ macro_rules! crash(
#[macro_export]
macro_rules! exit(
($exitcode:expr) => ({
unsafe { ::libc::exit($exitcode); }
unsafe { self::libc::exit($exitcode); }
})
)

View file

@ -1,10 +1,12 @@
#![allow(non_camel_case_types)]
#![allow(dead_code)]
extern crate libc;
pub use self::utmpx::{DEFAULT_FILE,USER_PROCESS,BOOT_TIME,c_utmp};
#[cfg(target_os = "linux")]
mod utmpx {
use libc;
use super::libc;
pub static DEFAULT_FILE: &'static str = "/var/run/utmp";
@ -25,30 +27,30 @@ mod utmpx {
pub static ACCOUNTING: libc::c_short = 9;
pub struct c_exit_status {
e_termination: libc::c_short,
e_exit: libc::c_short,
pub e_termination: libc::c_short,
pub e_exit: libc::c_short,
}
pub struct c_utmp {
ut_type: libc::c_short,
ut_pid: libc::pid_t,
ut_line: [libc::c_char, ..UT_LINESIZE],
ut_id: [libc::c_char, ..UT_IDSIZE],
pub ut_type: libc::c_short,
pub ut_pid: libc::pid_t,
pub ut_line: [libc::c_char, ..UT_LINESIZE],
pub ut_id: [libc::c_char, ..UT_IDSIZE],
ut_user: [libc::c_char, ..UT_NAMESIZE],
ut_host: [libc::c_char, ..UT_HOSTSIZE],
ut_exit: c_exit_status,
ut_session: libc::c_long,
ut_tv: libc::timeval,
pub ut_user: [libc::c_char, ..UT_NAMESIZE],
pub ut_host: [libc::c_char, ..UT_HOSTSIZE],
pub ut_exit: c_exit_status,
pub ut_session: libc::c_long,
pub ut_tv: libc::timeval,
ut_addr_v6: [libc::int32_t, ..4],
__unused: [libc::c_char, ..20],
pub ut_addr_v6: [libc::int32_t, ..4],
pub __unused: [libc::c_char, ..20],
}
}
#[cfg(target_os = "macos")]
mod utmpx {
use libc;
use super::libc;
pub static DEFAULT_FILE: &'static str = "/var/run/utmpx";
@ -69,19 +71,19 @@ mod utmpx {
pub static ACCOUNTING: libc::c_short = 9;
pub struct c_exit_status {
e_termination: libc::c_short,
e_exit: libc::c_short,
pub e_termination: libc::c_short,
pub e_exit: libc::c_short,
}
pub struct c_utmp {
ut_user: [libc::c_char, ..UT_NAMESIZE],
ut_id: [libc::c_char, ..UT_IDSIZE],
ut_line: [libc::c_char, ..UT_LINESIZE],
ut_pid: libc::pid_t,
ut_type: libc::c_short,
ut_tv: libc::timeval,
ut_host: [libc::c_char, ..UT_HOSTSIZE],
__unused: [libc::c_char, ..16]
pub ut_user: [libc::c_char, ..UT_NAMESIZE],
pub ut_id: [libc::c_char, ..UT_IDSIZE],
pub ut_line: [libc::c_char, ..UT_LINESIZE],
pub ut_pid: libc::pid_t,
pub ut_type: libc::c_short,
pub ut_tv: libc::timeval,
pub ut_host: [libc::c_char, ..UT_HOSTSIZE],
pub __unused: [libc::c_char, ..16]
}
}

View file

@ -40,9 +40,9 @@ struct Options {
// this takes `my_stat` to avoid having to stat files multiple times.
fn du(path: &Path, mut my_stat: FileStat,
options: Arc<Options>, depth: uint) -> ~[Arc<FileStat>] {
let mut stats = ~[];
let mut futures = ~[];
options: Arc<Options>, depth: uint) -> Vec<Arc<FileStat>> {
let mut stats = vec!();
let mut futures = vec!();
if my_stat.kind == TypeDirectory {
let read = match fs::readdir(path) {
@ -50,7 +50,7 @@ fn du(path: &Path, mut my_stat: FileStat,
Err(e) => {
safe_writeln!(&mut stderr(), "{}: cannot read directory {}: {}",
options.program_name, path.display(), e);
return ~[Arc::new(my_stat)]
return vec!(Arc::new(my_stat))
}
};
@ -70,7 +70,7 @@ fn du(path: &Path, mut my_stat: FileStat,
}
for future in futures.mut_iter() {
for stat in future.get().move_rev_iter() {
for stat in future.get().move_iter().rev() {
if !options.separate_dirs && stat.path.dir_path() == my_stat.path {
my_stat.size += stat.size;
my_stat.unstable.blocks += stat.unstable.blocks;
@ -229,8 +229,8 @@ ers of 1000).",
Some(s) => {
let mut found_number = false;
let mut found_letter = false;
let mut numbers = ~[];
let mut letters = ~[];
let mut numbers = vec!();
let mut letters = vec!();
for c in s.chars() {
if found_letter && c.is_digit() || !found_number && !c.is_digit() {
println!("{}: invalid --block-size argument '{}'", program, s);
@ -243,8 +243,8 @@ ers of 1000).",
letters.push(c);
}
}
let number = std::uint::parse_bytes(numbers, 10).unwrap();
let multiple = match std::str::from_chars(letters).as_slice() {
let number = std::uint::parse_bytes(numbers.as_slice(), 10).unwrap();
let multiple = match std::str::from_chars(letters.as_slice()).as_slice() {
"K" => 1024, "M" => 1024 * 1024, "G" => 1024 * 1024 * 1024,
"T" => 1024 * 1024 * 1024 * 1024, "P" => 1024 * 1024 * 1024 * 1024 * 1024,
"E" => 1024 * 1024 * 1024 * 1024 * 1024 * 1024,

View file

@ -27,8 +27,8 @@ fn print_char(c: char) {
print!("{}", c);
}
fn to_char(bytes: &[u8], base: uint) -> char {
uint::parse_bytes(bytes, base).unwrap() as u8 as char
fn to_char(bytes: &Vec<u8>, base: uint) -> char {
uint::parse_bytes(bytes.as_slice(), base).unwrap() as u8 as char
}
fn isxdigit(c: u8) -> bool {
@ -53,20 +53,20 @@ fn convert_str(string: &str, index: uint, base: uint) -> (char, int) {
_ => fail!(),
};
let mut bytes: ~[u8] = ~[];
let mut bytes = vec!();
for offset in range(0, max_digits) {
let c = string[index + offset as uint];
if is_legal_digit(c) {
bytes.push(c as u8);
} else {
if bytes.len() > 0 {
return (to_char(bytes, base), offset);
return (to_char(&bytes, base), offset);
} else {
return (' ', offset);
}
}
}
return (to_char(bytes, base), max_digits)
return (to_char(&bytes, base), max_digits)
}
fn main() {

14
env/env.rs vendored
View file

@ -16,9 +16,9 @@
struct options {
ignore_env: bool,
null: bool,
unsets: ~[~str],
sets: ~[(~str, ~str)],
program: ~[~str]
unsets: Vec<~str>,
sets: Vec<(~str, ~str)>,
program: Vec<~str>
}
fn usage(prog: &str) {
@ -59,9 +59,9 @@ fn main() {
let mut opts = ~options {
ignore_env: false,
null: false,
unsets: ~[],
sets: ~[],
program: ~[]
unsets: vec!(),
sets: vec!(),
program: vec!()
};
let mut wait_cmd = false;
@ -191,7 +191,7 @@ fn main() {
}
if opts.program.len() >= 1 {
match std::io::process::Process::status(opts.program[0].as_slice(), opts.program.slice_from(1)) {
match std::io::process::Process::status(opts.program.get(0).as_slice(), opts.program.slice_from(1)) {
Ok(exit) =>
std::os::set_exit_status(match exit {
std::io::process::ExitStatus(s) => s,

View file

@ -76,17 +76,16 @@ fn main() {
}
fn handle_obsolete(args: ~[~str]) -> (~[~str], Option<~str>) {
let mut args = args;
let mut args: Vec<~str> = args.move_iter().collect();
let mut i = 0;
while i < args.len() {
if args[i].char_at(0) == '-' && args[i].len() > 1 && args[i].char_at(1).is_digit() {
let mut removed = args.remove(i).unwrap();
removed.shift_char();
return (args, Some(removed));
if args.get(i).char_at(0) == '-' && args.get(i).len() > 1 && args.get(i).char_at(1).is_digit() {
return (args.as_slice().to_owned(),
Some(args.remove(i).unwrap().slice_from(1).to_owned()));
}
i += 1;
}
(args, None)
(args.as_slice().to_owned(), None)
}
fn fold(filenames: Vec<~str>, bytes: bool, spaces: bool, width: uint) {
@ -103,12 +102,12 @@ fn fold(filenames: Vec<~str>, bytes: bool, spaces: bool, width: uint) {
fn fold_file<T: io::Reader>(file: BufferedReader<T>, bytes: bool, spaces: bool, width: uint) {
let mut file = file;
for line in file.lines() {
let mut line = safe_unwrap!(line);
let line = safe_unwrap!(line);
if line.len() == 1 {
println!("");
continue;
}
line.pop_char();
let line = line.slice_to(line.len() - 1);
if bytes {
let mut i = 0;
while i < line.len() {
@ -128,27 +127,28 @@ fn fold_file<T: io::Reader>(file: BufferedReader<T>, bytes: bool, spaces: bool,
i += slice.len();
}
} else {
let mut output = ~"";
let mut output = StrBuf::new();
let mut count = 0;
for (i, ch) in line.chars().enumerate() {
match ch {
'\t' => {
count += 8;
if count > width {
println!("{}", output);
output = ~"";
println!("{}", output.as_slice());
output.truncate(0);
count = 8;
}
}
'\x08' => {
if count > 0 {
count -= 1;
output.pop_char();
let len = output.len() - 1;
output.truncate(len);
}
continue;
}
'\r' => {
output = ~"";
output.truncate(0);
count = 0;
continue;
}
@ -157,23 +157,24 @@ fn fold_file<T: io::Reader>(file: BufferedReader<T>, bytes: bool, spaces: bool,
output.push_char(ch);
if count == width {
let (val, ncount) = {
let slice = output.as_slice();
let (out, val, ncount) =
if spaces && i + 1 != line.len() {
match output.rfind(|ch: char| ch.is_whitespace()) {
match slice.rfind(|ch: char| ch.is_whitespace()) {
Some(m) => {
let routput = output.slice_from(m + 1).to_owned();
let routput = slice.slice_from(m + 1).to_owned();
let ncount = routput.chars().fold(0, |out, ch: char| out + if ch == '\t' { 8 } else { 1 });
(output.slice_to(m + 1), routput, ncount)
(slice.slice_to(m + 1), routput, ncount)
},
None => (output.as_slice(), ~"", 0)
None => (slice, ~"", 0)
}
} else {
(output.as_slice(), ~"", 0)
(slice, ~"", 0)
};
println!("{}", out);
(val, ncount)
};
output = val;
output = val.into_strbuf();
count = ncount;
}
}

View file

@ -11,7 +11,7 @@
#![feature(macro_rules)]
extern crate getopts;
extern crate libc;
//extern crate libc;
use std::os;
use getopts::{

View file

@ -25,14 +25,14 @@ static PROGRAM: &'static str = "head";
fn main () {
let args = os::args();
let mut options = args.tail().to_owned();
let options = args.tail().to_owned();
let mut line_count = 10u;
// handle obsolete -number syntax
match obsolete(&mut options) {
Some(n) => { line_count = n },
None => {}
}
let options = match obsolete(options) {
(args, Some(n)) => { line_count = n; args },
(args, None) => args
};
let possible_options = [
optopt("n", "number", "Number of lines to print", "n"),
@ -97,13 +97,14 @@ fn main () {
//
// In case is found, the options vector will get rid of that object so that
// getopts works correctly.
fn obsolete (options: &mut ~[~str]) -> Option<uint> {
fn obsolete (options: ~[~str]) -> (~[~str], Option<uint>) {
let mut options: Vec<~str> = options.move_iter().collect();
let mut a = 0;
let b = options.len();
let mut current;
while a < b {
current = options[a].clone();
current = options.get(a).clone();
if current.len() > 1 && current[0] == '-' as u8 {
let len = current.len();
@ -115,7 +116,7 @@ fn obsolete (options: &mut ~[~str]) -> Option<uint> {
if pos == len - 1 {
options.remove(a);
let number : Option<uint> = from_str(current.slice(1,len));
return Some(number.unwrap());
return (options.as_slice().to_owned(), Some(number.unwrap()));
}
}
}
@ -123,7 +124,7 @@ fn obsolete (options: &mut ~[~str]) -> Option<uint> {
a += 1;
};
None
(options.as_slice().to_owned(), None)
}
fn head<T: Reader> (reader: &mut BufferedReader<T>, line_count:uint) {

View file

@ -16,18 +16,18 @@
#![allow(non_camel_case_types)]
#![feature(macro_rules)]
extern crate getopts;
extern crate libc;
use std::{libc, os};
use std::os;
use std::ptr::read;
use std::libc::{
use libc::{
c_char,
c_int,
uid_t,
getgid,
getegid,
getuid,
getlogin
getuid
};
use libc::funcs::posix88::unistd::{getegid, geteuid, getgroups, getlogin};
use std::str::raw::from_c_str;
use getopts::{getopts, optflag, usage};
use c_types::{
@ -44,7 +44,7 @@ use c_types::{
#[cfg(not(target_os = "linux"))]
mod audit {
pub use std::mem::uninit;
use std::libc::{uid_t, pid_t, c_int, c_uint, uint64_t, dev_t};
use libc::{uid_t, pid_t, c_int, c_uint, uint64_t, dev_t};
pub type au_id_t = uid_t;
pub type au_asid_t = pid_t;
@ -53,22 +53,22 @@ mod audit {
pub type au_class_t = c_int;
pub struct au_mask {
am_success: c_uint,
am_failure: c_uint
pub am_success: c_uint,
pub am_failure: c_uint
}
pub type au_mask_t = au_mask;
pub struct au_tid_addr {
port: dev_t,
pub port: dev_t,
}
pub type au_tid_addr_t = au_tid_addr;
pub struct c_auditinfo_addr {
ai_auid: au_id_t, /* Audit user ID */
ai_mask: au_mask_t, /* Audit masks. */
ai_termid: au_tid_addr_t, /* Terminal ID. */
ai_asid: au_asid_t, /* Audit session ID. */
ai_flags: uint64_t /* Audit session flags */
pub ai_auid: au_id_t, /* Audit user ID */
pub ai_mask: au_mask_t, /* Audit masks. */
pub ai_termid: au_tid_addr_t, /* Terminal ID. */
pub ai_asid: au_asid_t, /* Audit session ID. */
pub ai_flags: uint64_t /* Audit session flags */
}
pub type c_auditinfo_addr_t = c_auditinfo_addr;
@ -327,7 +327,7 @@ fn id_print(possible_pw: Option<c_passwd>,
unsafe { getgrouplist(pw_name, gid, groups.as_ptr(), &mut ngroups) };
} else {
ngroups = unsafe {
libc::getgroups(NGROUPS, groups.as_mut_ptr() as *mut u32)
getgroups(NGROUPS, groups.as_mut_ptr() as *mut u32)
};
}
@ -348,7 +348,7 @@ fn id_print(possible_pw: Option<c_passwd>,
unsafe { from_c_str(read(gr).gr_name) });
}
let euid = unsafe { libc::geteuid() };
let euid = unsafe { geteuid() };
if p_euid && (euid != uid as u32) {
print!(" euid={:u}", euid);
let pw = unsafe { getpwuid(euid as i32) };

View file

@ -31,10 +31,7 @@ use getopts::{
usage,
};
use signals::{
ALL_SIGNALS,
DEFAULT_SIGNAL,
};
use signals::ALL_SIGNALS;
mod signals;
@ -47,8 +44,6 @@ static VERSION: &'static str = "0.0.1";
static EXIT_OK: i32 = 0;
static EXIT_ERR: i32 = 1;
pub enum Mode {
Kill,
Table,
@ -185,13 +180,10 @@ fn signal_by_name_or_value(signal_name_or_value:~str) -> Option<uint> {
fn kill(signalname: ~str, pids: std::vec::Vec<~str>) {
let optional_signal_value = signal_by_name_or_value(signalname.clone());
let mut signal_value:uint = DEFAULT_SIGNAL;
match optional_signal_value {
Some(x) => signal_value = x,
None => {
crash!(EXIT_ERR, "unknown signal name {}", signalname)
}
}
let signal_value = match optional_signal_value {
Some(x) => x,
None => crash!(EXIT_ERR, "unknown signal name {}", signalname)
};
for pid in pids.iter() {
match from_str::<i32>(*pid) {
Some(x) => {
@ -201,9 +193,7 @@ fn kill(signalname: ~str, pids: std::vec::Vec<~str>) {
Err(_) => ()
};
},
None => {
crash!(EXIT_ERR, "failed to parse argument {}", signalname)
},
None => crash!(EXIT_ERR, "failed to parse argument {}", signalname)
};
}
}

View file

@ -7,6 +7,8 @@
* that was distributed with this source code.
*/
#![allow(dead_code)]
pub static DEFAULT_SIGNAL:uint = 15;

View file

@ -127,16 +127,12 @@ fn exec(dirs: Vec<~str>, mk_parents: bool, mode: u32, verbose: bool) {
mkdir(&path, mode);
if verbose {println!("{}", *dir);}
} else if !mk_parents {
let mut error_msg = ~"";
if !parent_exists {
error_msg.push_str("parent directory '");
error_msg.push_str(parent);
error_msg.push_str("' does not exist");
} else {
error_msg.push_str("directory '");
error_msg.push_str(*dir);
error_msg.push_str("' already exists");
}
let error_msg =
if !parent_exists {
format!("parent directory '{}' does not exist", parent)
} else {
format!("directory '{}' already exists", *dir)
};
show_error!(1, "{}", error_msg);
}
}

View file

@ -76,8 +76,7 @@ fn paste(filenames: Vec<~str>, serial: bool, delimiters: ~str) {
};
delim_count += 1;
}
output.pop_char();
println!("{}", output);
println!("{}", output.slice_to(output.len() - 1));
}
} else {
let mut eof = Vec::from_elem(files.len(), false);
@ -104,8 +103,7 @@ fn paste(filenames: Vec<~str>, serial: bool, delimiters: ~str) {
if files.len() == eof_count {
break;
}
output.pop_char();
println!("{}", output);
println!("{}", output.slice_to(output.len() - 1));
delim_count = 0;
}
}

View file

@ -4,27 +4,27 @@ use std::str;
#[test]
fn test_count_up() {
let p = Process::output("build/seq", [~"10"]).unwrap();
let out = str::from_utf8(p.output).unwrap().into_owned();
let out = str::from_utf8(p.output.as_slice().to_owned()).unwrap().into_owned();
assert_eq!(out, ~"1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n");
}
#[test]
fn test_count_down() {
let p = Process::output("build/seq", [~"--", ~"5", ~"-1", ~"1"]).unwrap();
let out = str::from_utf8(p.output).unwrap().into_owned();
let out = str::from_utf8(p.output.as_slice().to_owned()).unwrap().into_owned();
assert_eq!(out, ~"5\n4\n3\n2\n1\n");
}
#[test]
fn test_separator_and_terminator() {
let p = Process::output("build/seq", [~"-s", ~",", ~"-t", ~"!", ~"2", ~"6"]).unwrap();
let out = str::from_utf8(p.output).unwrap().into_owned();
let out = str::from_utf8(p.output.as_slice().to_owned()).unwrap().into_owned();
assert_eq!(out, ~"2,3,4,5,6!");
}
#[test]
fn test_equalize_widths() {
let p = Process::output("build/seq", [~"-w", ~"5", ~"10"]).unwrap();
let out = str::from_utf8(p.output).unwrap().into_owned();
let out = str::from_utf8(p.output.as_slice().to_owned()).unwrap().into_owned();
assert_eq!(out, ~"05\n06\n07\n08\n09\n10\n");
}

View file

@ -15,7 +15,6 @@ extern crate getopts;
extern crate libc;
use std::num;
use std::cast;
use std::os;
use std::io::{print, timer};
@ -65,7 +64,7 @@ specified by the sum of their values.", opts));
fn sleep(args: Vec<~str>) {
let sleep_time = args.iter().fold(0.0, |result, arg| {
let suffix_time = match match_suffix(unsafe { cast::transmute(arg) }) {
let (arg, suffix_time) = match match_suffix(arg) {
Ok(m) => m,
Err(f) => {
crash!(1, "{}", f)
@ -75,10 +74,10 @@ fn sleep(args: Vec<~str>) {
if suffix_time == 0 {
0.0
} else {
match num::from_str_radix::<f64>((*arg), 10) {
match num::from_str_radix::<f64>((arg), 10) {
Some(m) => m,
None => {
crash!(1, "Invalid time interval '{}'", *arg)
crash!(1, "Invalid time interval '{}'", arg)
}
}
};
@ -87,20 +86,19 @@ fn sleep(args: Vec<~str>) {
timer::sleep((sleep_time * 1000.0) as u64);
}
fn match_suffix(arg: &mut ~str) -> Result<int, ~str> {
let result = match (*arg).pop_char().unwrap() {
's' | 'S' => Ok(1),
'm' | 'M' => Ok(60),
'h' | 'H' => Ok(60 * 60),
'd' | 'D' => Ok(60 * 60 * 24),
fn match_suffix(arg: &~str) -> Result<(~str, int), ~str> {
let result = match (*arg).char_at_reverse(0) {
's' | 'S' => 1,
'm' | 'M' => 60,
'h' | 'H' => 60 * 60,
'd' | 'D' => 60 * 60 * 24,
val => {
(*arg).push_char(val);
if !val.is_alphabetic() {
return Ok(1)
return Ok(((*arg).clone(), 1))
} else {
return Err(format!("Invalid time interval '{}'", *arg))
return Err(format!("Invalid time interval '{}'", arg))
}
}
};
result
Ok(((*arg).slice_to((*arg).len() - 1).to_owned(), result))
}

View file

@ -70,7 +70,11 @@ fn tac(filenames: Vec<~str>, before: bool, _: bool, separator: ~str) {
crash_if_err!(1, io::File::open(&Path::new(filename))));
let mut data = crash_if_err!(1, file.read_to_str());
if data.ends_with("\n") {
data.pop_char(); // removes blank line that is inserted otherwise
// removes blank line that is inserted otherwise
let mut buf = data.into_strbuf();
let len = buf.len();
buf.truncate(len - 1);
data = buf.into_owned();
}
let split_vec: ~[&str] = data.split_str(separator).collect();
let rev: ~str = split_vec.rev_iter().fold(~"", |a, &b|

View file

@ -57,7 +57,7 @@ fn options(args: &[~str]) -> Result<Options, ()> {
let help = format!("{}\n\nUsage:\n {} {}\n\n{}\n{}",
version, program, arguments, usage(brief, opts),
comment);
let names = std::vec::append_one(m.free.clone(), ~"-");
let names = m.free.clone().move_iter().collect::<Vec<~str>>().append_one(~"-").as_slice().to_owned();
let to_print = if m.opt_present("help") { Some(help) }
else if m.opt_present("version") { Some(version) }
else { None };

View file

@ -78,7 +78,7 @@ fn main() {
return;
}
let uname = unsafe { getuname() };
let mut output = ~"";
let mut output = StrBuf::new();
if matches.opt_present("sysname") || matches.opt_present("all")
|| !matches.opts_present([~"nodename", ~"release", ~"version", ~"machine"]) {
output.push_str(uname.sysname);
@ -101,5 +101,5 @@ fn main() {
output.push_str(uname.machine);
output.push_str(" ");
}
println!("{}", output.trim_left())
println!("{}", output.as_slice().trim_left())
}

View file

@ -15,13 +15,14 @@
#![feature(macro_rules, globs)]
extern crate getopts;
extern crate libc;
use std::os;
use std::cast::transmute;
use std::io::{print,File};
use std::libc::{time_t,c_double,c_int,c_char};
use std::io::{print, File};
use std::ptr::null;
use std::from_str::from_str;
use libc::{time_t, c_double, c_int, c_char};
use c_types::c_tm;
use utmpx::*;
@ -89,7 +90,7 @@ fn print_loadavg() {
else {
print!("load average: ")
for n in range(0, loads) {
print!("{:.2f}{}", avg[n], if n == loads - 1 { "\n" }
print!("{:.2f}{}", avg[n as uint], if n == loads - 1 { "\n" }
else { ", " } );
}
}

View file

@ -17,10 +17,10 @@
#![feature(macro_rules, globs)]
extern crate getopts;
extern crate libc;
use std::io::print;
use std::cast;
use std::libc;
use std::os;
use std::ptr;
use std::str;
@ -90,7 +90,7 @@ fn exec(filename: &str) {
}
});
let mut users: ~[~str] = ~[];
let mut users = vec!();
unsafe {
setutxent();

View file

@ -94,7 +94,7 @@ pub fn wc(files: Vec<~str>, matches: &Matches) {
let mut total_byte_count: uint = 0;
let mut total_longest_line_length: uint = 0;
let mut results: ~[Result] = ~[];
let mut results = vec!();
let mut max_str_len: uint = 0;
for path in files.iter() {
@ -123,14 +123,14 @@ pub fn wc(files: Vec<~str>, matches: &Matches) {
byte_count += raw_line.iter().len();
// try and convert the bytes to UTF-8 first
match from_utf8(raw_line) {
match from_utf8(raw_line.as_slice()) {
Some(line) => {
word_count += line.words().len();
current_char_count = line.chars().len();
char_count += current_char_count;
},
None => {
word_count += raw_line.split(|&x| is_word_seperator(x)).len();
word_count += raw_line.as_slice().split(|&x| is_word_seperator(x)).len();
for byte in raw_line.iter() {
match byte.is_ascii() {
true => {

View file

@ -16,11 +16,11 @@
#![feature(macro_rules)]
extern crate getopts;
extern crate libc;
use std::io::print;
use std::os;
use std::str;
use std::libc;
use c_types::{c_passwd, getpwuid};
#[path = "../common/util.rs"] mod util;