Skip to content

A const-friendly Rust macro for C string literals.

License

Notifications You must be signed in to change notification settings

notpeelz/cstr-literal

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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()) };
}
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].

About

A const-friendly Rust macro for C string literals.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Languages