Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I extract a number in decimal representation from a `&[u8]` and compare it with an integer?

Here’s an example of my code:

use bytes::Bytes;
use regex::bytes::Regex as BytesRegex;

fn main() {
    let val = b"2020-01-01";
    let my_regex = BytesRegex::new(r"\d{4}-(\d{2})-\d{2}").unwrap();
    let month = my_regex.captures(val).unwrap().get(1).unwrap();
    let month_digit = std::str::from_utf8(month.as_bytes()).unwrap().parse::<u8>().unwrap();
    println!("month smaller than 12: {}", month_digit<=12);
}

https://gist.github.com/rust-play/92d4e4855015317451abad775adceec1

Like this, I was able to print out the captured group as an unsigned integer. But, I had to go via std::str::from_utf8.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a way to get the same result without converting to str?

>Solution :

This can be done easily with Iterator::fold and basic arithmetic:

let month_digit = month.as_bytes().iter().fold (0, |acc, c| acc*10 + (c - '0' as u8))

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading