cstr-literal

crates.io license

This crate provides cstr!, a const-friendly macro for C string literals.

Compiler support: requires rustc 1.64+

Why?

Rust doesn't have C string literals (yet).

As of writing this, there's a couple cstr! macros floating around, but they all have their own set of drawbacks (unmaintained, no const support, nightly-only, overly complex/buggy, etc.)

Examples

Simple literal

```rust use core::ffi::CStr; use cstr_literal::cstr;

const STR: &CStr = cstr!("test");

fn test() { asserteq!(STR.tobyteswithnul(), b"test\0"); } ```

With references to other const items

```rust use core::ffi::{cchar, CStr}; use cstrliteral::cstr;

const ALLOCATOR: &str = "malloc";

extern "C" { fn useallocator(name: *const cchar); }

fn test() { unsafe { useallocator(cstr!(ALLOCATOR).asptr()) }; } ```

With const_format

```rust use core::ffi::CStr; use cstrliteral::cstr; use constformat::formatcp;

const VERSION: &CStr = { const PKGVERSION: &str = env!("CARGOPKGVERSION"); const GITHEAD: &str = "47007ba"; cstr!(formatcp!("{PKGVERSION}+{GITHEAD}")) };

fn test() { asserteq!(VERSION.tobyteswithnul(), b"0.1.0+47007ba\0"); } ```

No-std support

Thanks to rust#94079, this crate is unconditionally #![no_std].