#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

#224 in FFI

Download history 11/week @ 2024-07-28 10/week @ 2024-08-04 1/week @ 2024-08-11 4/week @ 2024-08-25 36/week @ 2024-09-29 14/week @ 2024-10-06 18/week @ 2024-10-13 11/week @ 2024-10-20 16/week @ 2024-10-27 7/week @ 2024-11-03

53 downloads per month
Used in after-effects

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

~530KB