-
Notifications
You must be signed in to change notification settings - Fork 13.2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Strings are not optimized as vector of characters #75618
Comments
You want |
But I need characters, not bytes :) |
I don't know if rustc could be able to decode utf-8 at compile time. |
A String conceptually wraps a Vec of u8s, a char wraps a u32, so a Vec of chars would be a non-optimization for most purposes, pretty sure. Can you not render a char literal? I assume the answer is "no" and that this is more complicated than it sounds, here. |
Oh I was no way suggesting that a str should represent a Vec, I see putting it like that was unfortunate. Instead, what I want from rustc is to understand that a "literal".chars() could be treated similarly. Iterating through characters and elements of a vector are optimized radically differently, and as I understand (and as @lzutao said) I was kind of expecting this since rustc/llvm inlines and optimizes a lot of non-const code so I was a bit surprised when this one didn't. |
Looks like this is caused by |
You can convert a string to an array of chars by const-evaluation. See const_str::to_char_array pub fn sum(chars: &[char]) -> u32 {
chars.iter().map(|&c| c as u32).sum()
}
const S: &str = "中文English🤣";
pub fn s() -> u32 {
sum(&const_str::to_char_array!(S))
}
#[test]
fn test() {
let chars = S.chars().collect::<Vec<_>>();
assert_eq!(s(), sum(&chars))
} |
This might be a long shot, but it would be really nice if Rust could do this. I'm working on an embedded application, where I draw some text. For a single symbol, I need to use a different font than I use to draw the rest of the text. Right now, Rust doesn't know that I use a single character and the binary contains all of the unnecessary text processing code to map that character to an index and to draw it.
It would be really cool if Rust could recognize that my string is a constant instead of a black box value.
I've reduced an example: https://rust.godbolt.org/z/GrnE79
The text was updated successfully, but these errors were encountered: