cstr-literal

Crates.iocstr-literal
lib.rscstr-literal
version0.1.0
sourcesrc
created_at2023-06-01 01:09:11.420653
updated_at2023-06-01 01:09:11.420653
descriptionA const-friendly macro for C string literals.
homepage
repositoryhttps://github.com/notpeelz/cstr-literal
max_upload_size
id879364
size9,084
peelz (notpeelz)

documentation

README

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].

Commit count: 1

cargo fmt