Does Rust provide the ability to parse integers directly from ASCII data in byte arrays (u8)?

Rust has FromStr , however, as far as I can see, it only requires text input in Unicode. Is there an equivalent to this for arrays [u8] ?

By "parse" I mean take ASCII characters and return an integer, such as C atoi .

Or I need either ...

  • First convert the u8 array to a string, then call FromStr .
  • Call libc atoi .
  • Write atoi in Rust.

In almost all cases, the first option is reasonable, but there are cases when the files can be very large, without a predefined encoding ... or contain mixed binary files and text, where it is most simple to read integers in the form of bytes.

+7
string rust
source share
2 answers

No, the standard library does not have such a function, but it does not need it.

As pointed out in the comments, raw bytes can be converted to &str through:

None of them perform additional distribution. The first ensures that the bytes are valid UTF-8, the second does not. Everyone should use a validated form until profiling proves that this is a bottleneck, and then use an unverified form once it is safe to do so.

If bytes deeper in the data must be analyzed, a fragment of the raw bytes can be obtained before conversion:

 use std::str; fn main() { let raw_data = b"123132"; let the_bytes = &raw_data[1..4]; let the_string = str::from_utf8(the_bytes).expect("not UTF-8"); let the_number: u64 = the_string.parse().expect("not a number"); assert_eq!(the_number, 231); } 

As in other code, these lines can be extracted into a function or attribute to allow reuse. However, as soon as this path is followed, it would be nice to study one of the many great boxes designed for parsing . This is especially true if, in addition to text data, binary data needs to be analyzed.

+6
source share

I don’t know a single method in the standard library, but maybe atoi works for you?

 extern crate atoi; use atoi::atoi; let (number, digits) = atoi::<u32>(b"42 is the answer"); //returns (42,2) 

You can check if the second element of the tuple is zero to see if the slice begins with a digit.

 let (number, digits) = atoi::<u32>(b"x"); //returns (0,0) let (number, digits) = atoi::<u32>(b"0"); //returns (0,1) 
+1
source share

All Articles