String -> Octal parsing

Sorry if i choose wrong category, this is first time i'm writing there.

Problem:

In standard library we set files permissions trough octal u32 (ex. permissions.set_mode(0o644)).

And we have formatter for octal display - println!("{:o}").

But, language don't have anything to parse octals from strings - ex. "0o644" -> u32 (0o644)? maybe i'm wrong?.

Problem is: we can't get octal from external data sources, we can hardcode in our code only.

Suggestion: Implement it in standard parsing way.

There is u32::from_str_radix(input, 8), which does not specifically handle the "0o" prefix but that should be workable.

Edit: This is oddly an on-topic question for this forum, since you are proposing an addition to the standard library, but if you were only wondering how to parse octal in rust then you're probably looking for https://users.rust-lang.org/

2 Likes

Like in "TRUE" does not parse into boolean · Issue #101870 · rust-lang/rust · GitHub, I think it's best that we not change this to accept more, since people could be relying on it not parsing the prefix in parsers for various formats.

Adding an alternative method that looks for the prefix to decide the radix sounds useful, though. (But I don't know if libs-api would want it in core, vs leaving it for a crate to provide.)

The strtol family of functions in C autodetect the radix if the radix argument is zero, but of course such magic values aren’t very Rusty. A const BY_PREFIX: u32 = /* implementation detail */ might work, but yeah, a separate method would probably be the way to go.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.