relibc/byte_literal.rs
1use crate::platform::types::c_char;
2
3/// An abstraction over a byte literal to provide a method to convert safely
4/// to a `c_char`.
5///
6/// The abstraction is required so we can contain architecture specific code
7/// in a central location.
8pub struct ByteLiteral;
9
10impl ByteLiteral {
11 /// Casts a byte literal (`u8`) to a `c_char` without using `as`.
12 ///
13 /// # Panics
14 /// If `input` is not within the following range of ascii characters:
15 /// - Octal: `040`..=`176`
16 /// - Decimal: `30`..=`126`
17 /// - Hexadecimal: `20`..=`7E`
18 /// - Byte literals: The space character (` `) upto and including tilde (`~`)
19 pub fn cast_cchar(input: u8) -> c_char {
20 match input {
21 b' '..=b'~' => {
22 // `c_char` is an `i8` on these arches
23 #[cfg(any(target_arch = "x86_64", target_arch = "x86"))]
24 {
25 input.cast_signed()
26 }
27 // `c_char` is already a `u8` on these arches
28 #[cfg(any(target_arch = "aarch64", target_arch = "riscv64"))]
29 {
30 input.into()
31 }
32 }
33 _ => panic!("Not a printable ascii character!"),
34 }
35 }
36}