Non-decimal radices/Convert: Difference between revisions

Reduce the Rust code
(Add source for Rust)
(Reduce the Rust code)
Line 2,847:
 
=={{header|Rust}}==
Rust standard library provides parsing a string in a given radix to all integer types.
There is no reverse operation (except for format specifiers for binary, octal, decimal
and hexadecimal base).
 
<lang Rust>fn format_with_radix(mut n: u32, radix: u32) -> String {
assert!(2 <= radix && radix <= 36);
Line 2,861 ⟶ 2,865:
 
result.chars().rev().collect()
}
 
fn parse_with_radix<S: AsRef<str>>(s: S, radix: u32) -> Result<u32, S> {
assert!(2 <= radix && radix <= 36);
 
let mut result = 0;
for digit in s.as_ref().chars().map(|it| it.to_digit(radix)) {
match digit {
Some(value) => result = result * radix + value,
None => return Err(s),
}
}
 
Ok(result)
}
 
Line 2,883 ⟶ 2,873:
for radix in 2..=36 {
let s = format_with_radix(value, radix);
let v = parse_with_radixu32::from_str_radix(s.as_str(), radix).unwrap();
assert_eq!(value, v);
}
Line 2,893 ⟶ 2,883:
println!("{}", format_with_radix(0xdeadbeef, 36));
println!("{}", format_with_radix(0xdeadbeef, 16));
println!("{}", parse_with_radixu32::from_str_radix("DeadBeef", 16)?);
Ok(())
}</lang>
Anonymous user