Skip to content

Add cstr! macro for creating &'static CStrs. #103

Description

@reitermarkus

Proposal

Problem statement

Now that core::ffi::CStr is stabilized, there should be an ergonomic way to create &CStr constants.

Motivation, use-cases

On stable there is currently no good way to create a &'static CStr, the simplest solution needs unsafe, i.e.

const MY_C_STRING: &CStr = unsafe { CStr::from_bytes_with_nul_unchecked(b"Hello, world!\0") };

On nightly, it is possible since rust-lang/rust#100291 without unsafe, but these are even more verbose or don't provide meaningful error messages:

#![feature(const_cstr_methods)]

const MY_C_STRING: &CStr = if let Ok(s) = CStr::from_bytes_with_nul(b"Hello, world!\0") {
    s
} else {
    panic!("contains interior nul bytes")
};
#![feature(const_cstr_methods)]
#![feature(const_option)]

const MY_C_STRING: &CStr = CStr::from_bytes_with_nul(b"Hello, world!\0").ok().unwrap();

Solution sketches

With a cstr!, the example above becomes both easier to write and easier to read, i.e.

const MY_C_STRING: &CStr = cstr!("Hello, world!");

Links and related work

What happens now?

This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals in its weekly meeting. You should receive feedback within a week or two.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions