Optimize next Rust code: fn decdigit(x: u8) -> u8 { if (x < 48 x > 102) (x > 57 && x <…
- User
Optimize next Rust code: fn decdigit(x: u8) -> u8 { if (x < 48 || x > 102) || (x > 57 && x < 97) { return 0; } if x < 97 { x - 48 } else { x - 87 } }
Function must return u8 type.
- Assistant
The provided Rust function
decdigitchecks if the inputxis a valid decimal or hexadecimal digit (ASCII values for digits and letters) and returns a corresponding value. If the input is out of range, it returns0. We can optimize the function by reducing the number of conditions checked and avoiding some of the comparisons.Here's an optimized version of the code:
fn decdigit(x: u8) -> u8 { match x { 48..=57 => x - 48, // ASCII '0' (48) to '9' (57) 97..=102 => x - 87, // ASCII 'a' (97) to 'f' (102) _ => 0, // Out of range } }Explanation:
-
Pattern Matching: We use the
matchconstruct, which is generally more idiomatic in Rust for handling multiple conditions. It checks the value of against the specified ranges ( for '0' to '9' and for 'a' to 'f').
-