Character literal cast to u8 instead of written as a byte literal
ID |
rust.portability.char_lit_as_u8 |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Numeric Conversion |
Language |
Rust |
Description
Detects a char literal converted to a byte with an as u8 cast, for example ',' as u8, rather than being written directly as the byte literal b','.
Rationale
A char is a Unicode scalar value, so the cast only reproduces the intended byte while the character stays inside the ASCII range. Any character above U+00FF is truncated to its low byte without a warning, which silently corrupts the value and makes the code behave differently from the surrounding byte-oriented parsing it usually sits in.
The following code illustrates the pattern detected by this rule:
pub fn delimiters() -> [u8; 4] {
// FLAGGED: Character literal cast to u8 instead of written as a byte literal
let comma = ',' as u8;
// FLAGGED: Character literal cast to u8 instead of written as a byte literal
let newline = '\n' as u8;
// FLAGGED: Character literal cast to u8 instead of written as a byte literal
let quote = '\'' as u8;
// FLAGGED: Character literal cast to u8 instead of written as a byte literal
let zero = '0' as u8;
[comma, newline, quote, zero]
}