Skip to content
This repository has been archived by the owner on Mar 7, 2021. It is now read-only.

Introduce a less verbose, type safe, idiom for C strings. #133

Merged
merged 1 commit into from Aug 20, 2019
Merged

Conversation

alex
Copy link
Member

@alex alex commented Aug 20, 2019

Fixes #16

@alex alex force-pushed the c-str-idiom branch 2 times, most recently from 8cfa2a8 to 89dac48 Compare August 20, 2019 00:08
src/types.rs Outdated Show resolved Hide resolved
src/types.rs Outdated Show resolved Hide resolved
impl CStr {
pub fn new<'a>(data: &'a str) -> &'a CStr {
if data.bytes().position(|b| b == b'\x00') != Some(data.len() - 1) {
panic!("CStr must contain a single NUL byte at the end");
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, is it worth having two versions of this, one internal for cstr!(I think it needs to be #[doc(hidden)] pub) and one actually public that returns EINVAL instead of panicking?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As soon as we have another use case for this :-)

Also, cstr doesn't have a way to statically verify these things, so it can't bypass them at runtime either.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TBH I'd be okay with this being an unsafe function that assumes there's a trailing NUL, to get rid of the runtime cost. cstr! enforces it so it can safely call it.

@alex alex force-pushed the c-str-idiom branch 2 times, most recently from 0bf857f to 5237817 Compare August 20, 2019 00:27
@alex alex merged commit ae3d73c into master Aug 20, 2019
@alex alex deleted the c-str-idiom branch August 20, 2019 00:39
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

make C strings a little more ergonomic
2 participants