Skip to main content

parse_binary

Function parse_binary 

Source
pub fn parse_binary(on: &str) -> Result<usize, ()>
Examples found in repository?
examples/parse-number.rs (line 25)
6fn main() -> Result<(), Box<dyn std::error::Error>> {
7    let mut args = std::env::args().skip(1);
8    let value = args.next();
9    if let Some("--help") | None = value.as_deref() {
10        eprintln!(
11            "usage: `{BIN_NAME} *number*` or `{BIN_NAME} *number* (--roman | --binary | --hex | --english)`"
12        );
13        eprintln!("examples: `{BIN_NAME} seven`, `{BIN_NAME} IX --roman`");
14        eprintln!();
15        eprintln!("{AUTHOR} - 2025");
16        return Ok(());
17    }
18
19    let value = value.unwrap();
20
21    let next = args.next();
22    let format = next.as_deref().unwrap_or("--english");
23    let result = match format {
24        "--roman" => parse::parse_roman_numeral(&value),
25        "--binary" => parse::parse_binary(&value),
26        "--hex" => parse::parse_hex(&value),
27        "--english" => parse::parse_english(&value).map_err(|_| ()),
28        format => {
29            return Err(format!(
30                "unknown format {format}. expected --roman, --binary, --hex or --english"
31            )
32            .into());
33        }
34    };
35
36    if let Ok(value) = result {
37        println!("{value}");
38        Ok(())
39    } else {
40        return Err(format!("could not format {value} in format {format}").into());
41    }
42}