I am trying to parse space separated hex values in vec![]
, not able to figure out how to solve this.
Hex
0x00 0x01 0x03 0x03 0x0a 0x0d 0x1b 0x5d 0x18 0x18 0x18 0x1a 0x04 0x13 0x7f 0x80 0xfe 0xff
Result
[0, 1, 3, 3, 10, 13, 27, 93, 24, 24, 24, 26, 4, 19, 127, 128, 254]
Other format
Hex
<B[18] 0x00 0x01 0x03 0x03 0x0a 0x0d 0x1b 0x5d 0x18 0x18 0x18 0x1a 0x04 0x13 0x7f 0x80 0xfe 0xff>
I have tried this for
fn hex_to_u8(input: &str) -> IResult<&str, u8> {
let (input, _) = tag("0x")(input)?;
let (input, hex) = take_until(" ")(input)?;
let (input, _) = tag(" ")(input)?;
Ok((input, u8::from_str_radix(hex, 16).unwrap()))
}
Rust Playground link
// parse hex value 0x00 to 0xff into u8 value, which are separated by space, using nom
use nom::{
bytes::complete::{tag, take_until},
character::complete::multispace0,
combinator::map_res,
multi::many1,
IResult,
};
fn hex_to_u8(input: &str) -> IResult<&str, u8> {
}
fn parser(input: &str) -> IResult<&str, Vec<u8>> {
let (input, result) = many1(hex_to_u8)(input)?;
Ok((input, result))
}
fn bin_parser(input: &str) -> IResult<&str, Vec<u8>> {
let (input, _) = multispace0(input)?;
let (input, _) = tag("<B")(input)?;
let (input, _) = multispace0(input)?;
let (input, _) = tag("[")(input)?;
let (input, _) = take_until("]")(input)?;
let (input, _) = tag("]")(input)?;
let (input, _) = multispace0(input)?;
let (input, result) = many1(hex_to_u8)(input)?;
let (input, _) = multispace0(input)?;
let (input, _) = tag(">")(input)?;
Ok((input, result))
}
fn main() {
let input =
"0x00 0x01 0x03 0x03 0x0a 0x0d 0x1b 0x5d 0x18 0x18 0x18 0x1a 0x04 0x13 0x7f 0x80 0xfe 0xff";
let (_, result) = parser(input).unwrap();
println!("{:?}", result);
let bin = "<B[18] 0x00 0x01 0x03 0x03 0x0a 0x0d 0x1b 0x5d 0x18 0x18 0x18 0x1a 0x04 0x13 0x7f 0x80 0xfe 0xff>";
let (_, result) = bin_parser(bin).unwrap();
println!("{:?}", result);
let bin = "<B 0x00 0x01 0x03 0x03 0x0a 0x0d 0x1b 0x5d 0x18 0x18 0x18 0x1a 0x04 0x13 0x7f 0x80 0xfe 0xff>";
let (_, result) = bin_parser(bin).unwrap();
println!("{:?}", result);
let bin = "<B[0]>";
let (_, result) = bin_parser(bin).unwrap();
println!("{:?}", result);
let bin = "<B>";
let (_, result) = bin_parser(bin).unwrap();
println!("{:?}", result);
}