Joe232
1
I have this code over here:
const CMP: &str = "should";
const VALUE: &str = "should \n have\nshoulds";
const FINAL_VALUE: &str = const_str::replace!(VALUE, "\n", "");
const_str
is a library: const_str - Rust
Unfortunately const FINAL_VALUE: &str = const_str::replace!(VALUE, "\n", "");
will run once, and won't remove all the \n
enter characters.
The idea is that during compile time I want to split by line and then split by space and determine if certain words exist or not.
jofas
2
Not the prettiest, but it strips newline characters from a string slice:
const VALUE: &str = "should \n have\nshoulds";
const FINAL_VALUE_BYTES: [u8; len_without_newline(VALUE)] = bytes_without_newline(VALUE);
const FINAL_VALUE: &str = match std::str::from_utf8(&FINAL_VALUE_BYTES) {
Ok(res) => res,
Err(_) => panic!(),
};
const fn len_without_newline(s: &str) -> usize {
let s = s.as_bytes();
let mut i_val = 0;
let mut i_res = 0;
while i_val < s.len() {
if s[i_val] != '\n' as u8 {
i_res += 1;
}
i_val += 1;
}
i_res
}
const fn bytes_without_newline<const N: usize>(s: &str) -> [u8; N] {
let s = s.as_bytes();
let mut res = [0u8; N];
let mut i_val = 0;
let mut i_res = 0;
while i_val < s.len() {
if s[i_val] != '\n' as u8 {
res[i_res] = s[i_val];
i_res += 1;
}
i_val += 1;
}
res
}
fn main() {
assert_eq!(FINAL_VALUE, "should haveshoulds");
}
Playground.
2 Likes