coreutils/hostid/hostid.rs

116 lines
2.3 KiB
Rust
Raw Normal View History

2014-04-03 20:56:36 +00:00
#![crate_id(name="hostid", vers="0.0.1", author="Maciej Dziardziel")]
#![feature(macro_rules)]
#![feature(phase)]
/*
* This file is part of the uutils coreutils package.
*
* (c) Maciej Dziardziel <fiedzia@gmail.com>
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*/
extern crate getopts;
extern crate collections;
extern crate serialize;
extern crate libc;
2014-04-03 20:56:36 +00:00
#[phase(syntax, link)] extern crate log;
use std::os;
use getopts::{
getopts,
optflag,
usage,
};
use libc::{c_long};
2014-04-03 20:56:36 +00:00
#[path = "../common/util.rs"]
mod util;
static NAME: &'static str = "hostid";
static VERSION: &'static str = "0.0.1";
static EXIT_ERR: int = 1;
2014-04-03 20:56:36 +00:00
pub enum Mode {
HostId,
Help,
Version,
}
//currently rust libc interface doesn't include gethostid
extern {
pub fn gethostid() -> c_long;
}
#[allow(dead_code)]
fn main() { os::set_exit_status(uumain(os::args())); }
2014-05-28 11:43:37 +00:00
pub fn uumain(args: Vec<String>) -> int {
2014-04-03 20:56:36 +00:00
2014-05-23 12:28:40 +00:00
let opts = [
2014-04-03 20:56:36 +00:00
optflag("", "help", "display this help and exit"),
optflag("", "version", "output version information and exit"),
];
let usage = usage("[options]", opts);
let matches = match getopts(args.tail(), opts) {
Ok(m) => m,
Err(e) => {
show_errer!("{}\n{}", e.to_err_msg(), get_help_text(NAME, usage.as_slice()));
return EXIT_ERR;
2014-04-03 20:56:36 +00:00
},
};
let mode = if matches.opt_present("version") {
Version
} else if matches.opt_present("help") {
Help
} else {
HostId
};
match mode {
HostId => hostid(),
2014-05-17 10:32:14 +00:00
Help => help(NAME, usage.as_slice()),
2014-04-03 20:56:36 +00:00
Version => version(),
}
return 0;
2014-04-03 20:56:36 +00:00
}
fn version() {
println!("{} {}", NAME, VERSION);
}
2014-05-25 09:20:52 +00:00
fn get_help_text(progname: &str, usage: &str) -> String {
2014-05-23 12:28:40 +00:00
format!("Usage: \n {0} {1}", progname, usage)
2014-04-03 20:56:36 +00:00
}
fn help(progname: &str, usage: &str) {
println!("{}", get_help_text(progname, usage));
}
fn hostid() {
/* POSIX says gethostid returns a "32-bit identifier" but is silent
whether it's sign-extended. Turn off any sign-extension. This
is a no-op unless unsigned int is wider than 32 bits. */
let mut result:c_long;
unsafe {
result = gethostid();
}
result &= 0xffffffff;
println!("{:0>8x}", result);
}