Skip to content
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

Add CStr::from_bytes #1264

Closed
nagisa opened this issue Aug 22, 2015 · 3 comments
Closed

Add CStr::from_bytes #1264

nagisa opened this issue Aug 22, 2015 · 3 comments

Comments

@nagisa
Copy link
Member

nagisa commented Aug 22, 2015

Add a CStr::from_bytes function with a following API (or something along the lines):

enum CStrFromBytesError {
     InteriorNullBytes,
     NoEndingNullByte,
};
impl CStr {
    fn from_bytes(bytes: &[u8]) -> Result<&CStr, CStrFromBytesError>;
}

Which converts a bytestring with a trailing null byte to a C string slice. If the slice does not have a trailing null byte or has a null byte in any position that’s not the last byte appropriate error is returned.

This is useful in APIs where a &CStr is expected and you can/want to pass in a static string (e.g. b"helloworld\0").

@cristicbz
Copy link

Ooh, big 👍. I've on occasion written my own Cow version of c-strings which allocates iff there's an interior nul or missing terminating nul.

@oberien
Copy link

oberien commented Sep 16, 2015

IMO this should be implemented in a crate but not std. AFAIK there is no use case for converting a "rust"-string to a c-string other than passing it to other non-rust libraries, which need/expect a c-type string. Therefore having this conversion in std could result in "rust"-libs wanting to have a CStr, resulting in a lot of different types for each lib...

Is there some use case for CStr when writing solely in rust?

@nagisa
Copy link
Member Author

nagisa commented Aug 20, 2016

CStr::from_bytes_with_nul has been stabilised in 1.10 (rust-lang/rust#31190).

@nagisa nagisa closed this as completed Aug 20, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants