Skip to content

Commit 182c12b

Browse files
committed
Added octal format support and removed regex dependency
* Added support for converting from octal (0o…). * Added conversion to octal. * Simplified input parsing logic by replacing regex validation with direct format checks. * Removed unused regex dependency from `Cargo.toml`.
1 parent 5a6a394 commit 182c12b

File tree

2 files changed

+11
-17
lines changed

2 files changed

+11
-17
lines changed

Cargo.toml

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,3 @@ edition = "2024"
77
anyhow = "1.0.98"
88
clap = { version = "4.5.39", features = ["derive"] }
99
colored = "3.0.0"
10-
regex = "1.11.1"

src/main.rs

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
11
use clap::Parser;
2-
use regex::Regex;
3-
use std::i64;
42
use colored::Colorize;
5-
6-
const HEX_PATTERN: &str = r"^0x[0-9a-fA-F]+$";
7-
const DEC_PATTERN: &str = r"^-?[0-9]+$";
3+
use std::i64;
84

95
const FORMAT_DEC: &str = "Dec:\t{:#}";
106
const FORMAT_HEX: &str = "Hex:\t{:#x}";
117
const FORMAT_BIN: &str = "Bin:\t{:#b}";
8+
const FORMAT_OCT: &str = "Oct:\t{:#o}";
129

1310
#[derive(Debug, Parser)]
1411
#[command(author, version, about, long_about = None)]
@@ -29,15 +26,18 @@ fn main() {
2926
fn display_number_formats(value: i64, monochrome: bool) -> () {
3027
let dec_line = format_line(FORMAT_DEC, "{:#}", &value.to_string());
3128
let hex_line = format_line(FORMAT_HEX, "{:#x}", &format!("{:#x}", value));
29+
let oct_line = format_line(FORMAT_OCT, "{:#o}", &format!("{:#o}", value));
3230
let bin_line = format_line(FORMAT_BIN, "{:#b}", &format!("{:#b}", value));
3331

3432
if monochrome {
3533
println!("{}", dec_line);
3634
println!("{}", hex_line);
35+
println!("{}", oct_line);
3736
println!("{}", bin_line);
3837
} else {
3938
println!("{}", dec_line.bright_green());
4039
println!("{}", hex_line.bright_cyan());
40+
println!("{}", oct_line.yellow());
4141
println!("{}", bin_line.bright_magenta());
4242
}
4343
}
@@ -52,16 +52,11 @@ fn handle_parse_error(error: anyhow::Error) -> ! {
5252
}
5353

5454
fn parse_number(input: &str) -> anyhow::Result<i64> {
55-
let hex_reg_ex = Regex::new(HEX_PATTERN)?;
56-
let dec_reg_ex = Regex::new(DEC_PATTERN)?;
55+
let result = match input {
56+
s if s.starts_with("0x") || s.starts_with("0X") => i64::from_str_radix(&s[2..], 16),
57+
s if s.starts_with("0o") || s.starts_with("0O") => i64::from_str_radix(&s[2..], 8),
58+
s => s.parse::<i64>(),
59+
};
5760

58-
if !hex_reg_ex.is_match(input) && !dec_reg_ex.is_match(input) {
59-
anyhow::bail!("Invalid number format: {}", input);
60-
}
61-
62-
if hex_reg_ex.is_match(input) {
63-
Ok(i64::from_str_radix(&input.trim_start_matches("0x"), 16)?)
64-
} else {
65-
Ok(input.parse::<i64>()?)
66-
}
61+
result.map_err(|_| anyhow::anyhow!("Invalid number format"))
6762
}

0 commit comments

Comments
 (0)