Hi there!
Saw it across codebase I'm working on that ppl do:
CString::new(key.to_owned());
where key is &str. It leads to realloc as CString::new tries to add then \0. Ended up with utility function doing:
let mut s = String::with_capacity(key.len() + 1);
s.push_str(key);
CString::new(s)
Opinions on impl TryFrom so avoid such inefficiency?
3 Likes
This would also be suitable for no_std folks, as we don't like allocations at all
1 Like
bjorn3
3
When would the TryFrom
return an error under your proposal?
1 Like
In the same case like CString::new
returns NulError
currently (CString in std::ffi - Rust).
CString::new
can accepts a &str
, see playground.
1 Like
bjorn3
6
(Your playground link is broken. It doesn't link to any code.)
1 Like
Yup, seems there is already optimization inside if &str is passed to avoid realloc. So I need for extra TryFrom impl
system
Closed
9
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.