| 1 |
use nom::bytes::complete::{tag, take_while_m_n}; |
| 2 |
use nom::combinator::map_res; |
| 3 |
use nom::{IResult, Parser}; |
| 4 |
|
| 5 |
#[derive(Debug, Eq, PartialEq)] |
| 6 |
pub struct Color { |
| 7 |
pub red: u8, |
| 8 |
pub green: u8, |
| 9 |
pub blue: u8, |
| 10 |
} |
| 11 |
|
| 12 |
fn from_hex(input: &str) -> Result<u8, std::num::ParseIntError> { |
| 13 |
u8::from_str_radix(input, 16) |
| 14 |
} |
| 15 |
|
| 16 |
fn is_hex_digit(c: char) -> bool { |
| 17 |
c.is_ascii_hexdigit() |
| 18 |
} |
| 19 |
|
| 20 |
fn hex_primary(input: &str) -> IResult<&str, u8> { |
| 21 |
map_res(take_while_m_n(2, 2, is_hex_digit), from_hex).parse(input) |
| 22 |
} |
| 23 |
|
| 24 |
fn hex_color(input: &str) -> IResult<&str, Color> { |
| 25 |
let (input, _) = tag("#")(input)?; |
| 26 |
let (input, (red, green, blue)) = (hex_primary, hex_primary, hex_primary).parse(input)?; |
| 27 |
|
| 28 |
Ok((input, Color { red, green, blue })) |
| 29 |
} |
| 30 |
|
| 31 |
#[test] |
| 32 |
fn parse_color() { |
| 33 |
assert_eq!( |
| 34 |
hex_color("#2F14DF"), |
| 35 |
Ok(( |
| 36 |
"", |
| 37 |
Color { |
| 38 |
red: 47, |
| 39 |
green: 20, |
| 40 |
blue: 223, |
| 41 |
} |
| 42 |
)) |
| 43 |
); |
| 44 |
} |