#string-literal #literals #cstr #string #const #macro

no-std cstr-literal

A const-friendly macro for C string literals

1 unstable release

0.1.0 Jun 1, 2023

#218 in FFI

21 downloads per month

MIT license

5KB

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

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

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

fn test() {
  assert_eq!(STR.to_bytes_with_nul(), b"test\0");
}

With references to other const items

use core::ffi::{c_char, CStr};
use cstr_literal::cstr;

const ALLOCATOR: &str = "malloc";

extern "C" {
  fn use_allocator(name: *const c_char);
}

fn test() {
  unsafe { use_allocator(cstr!(ALLOCATOR).as_ptr()) };
}

With const_format

use core::ffi::CStr;
use cstr_literal::cstr;
use const_format::formatcp;

const VERSION: &CStr = {
  const PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
  const GIT_HEAD: &str = "47007ba";
  cstr!(formatcp!("{PKG_VERSION}+{GIT_HEAD}"))
};

fn test() {
  assert_eq!(VERSION.to_bytes_with_nul(), b"0.1.0+47007ba\0");
}

No-std support

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

Dependencies

~540KB