Skip to content

Commit 4ad5144

Browse files
committed
Don't panic on invalid sha1 strings.
1 parent 634d623 commit 4ad5144

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

src/main.rs

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,6 @@ struct Col {
3030
}
3131

3232
impl Col {
33-
fn new(sha: &str) -> Self {
34-
Self {
35-
r: i32::from_str_radix(&sha[0..2], 16).unwrap(),
36-
g: i32::from_str_radix(&sha[2..4], 16).unwrap(),
37-
b: i32::from_str_radix(&sha[4..6], 16).unwrap(),
38-
}
39-
}
40-
4133
fn rgb(&self) -> Color {
4234
Color::Rgb {
4335
r: self.r as u8,
@@ -47,6 +39,13 @@ impl Col {
4739
}
4840
}
4941

42+
fn parse_sha(sha: &str) -> Option<(i32, i32, i32)> {
43+
let r = i32::from_str_radix(&sha[0..2], 16).ok()?;
44+
let g = i32::from_str_radix(&sha[2..4], 16).ok()?;
45+
let b = i32::from_str_radix(&sha[4..6], 16).ok()?;
46+
Some((r, g, b))
47+
}
48+
5049
fn main() {
5150
let args: Vec<String> = env::args().collect();
5251
let argc = args.len();
@@ -68,10 +67,16 @@ fn main() {
6867
let code = &line[0..6];
6968
let name = &line[7..];
7069
names.push(name.to_string());
71-
rgbs.push(Col::new(code));
70+
if let Some((r, g, b)) = parse_sha(code) {
71+
rgbs.push(Col { r, g, b });
72+
}
73+
}
74+
if let Some((r, g, b)) = parse_sha(sha1) {
75+
let idx_closest = closest(&Col { r, g, b }, &rgbs);
76+
fill(sha1, &rgbs[idx_closest], &names[idx_closest], argc == 3);
77+
} else {
78+
println!("{sha1} is not a valid sha1")
7279
}
73-
let idx_closest = closest(&Col::new(sha1), &rgbs);
74-
fill(sha1, &rgbs[idx_closest], &names[idx_closest], argc == 3);
7580
}
7681

7782
fn fill(sha: &str, color: &Col, name: &str, oneline: bool) {

0 commit comments

Comments
 (0)