Impl TryFrom<&str> for CString

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

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

(Your playground link is broken. It doesn't link to any code.)

1 Like

Sorry, link fixed

Yup, seems there is already optimization inside if &str is passed to avoid realloc. So I need for extra TryFrom impl

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.