#string-literal #literals #optimization #c-compatible #libc #c-str #const-str

const-cstr-fork

Create static C-compatible strings from Rust string literals. Fork of https://github.com/abonander/const-cstr

1 unstable release

Uses old Rust 2015

0.2.2 Jun 1, 2017

#13 in #c-str

Download history 123/week @ 2024-04-01 43/week @ 2024-04-08 62/week @ 2024-04-15 63/week @ 2024-04-22 72/week @ 2024-04-29 82/week @ 2024-05-06 62/week @ 2024-05-13 64/week @ 2024-05-20 51/week @ 2024-05-27 49/week @ 2024-06-03 52/week @ 2024-06-10 63/week @ 2024-06-17 65/week @ 2024-06-24 37/week @ 2024-07-08 73/week @ 2024-07-15

179 downloads per month
Used in 23 crates (4 directly)

MIT/Apache

8KB
81 lines

const-cstr-fork

This crate has been forked from const-str to try to optimise performance in some scenarios. It may disappear or be merged back into const-cstr. Many thanks are due to constr-str's author for the original design.

Create static C-compatible strings from Rust string literals.

Usage

Cargo.toml:

[dependencies]
const-cstr-fork = "0.1"

Crate root:

#[macro_use] extern crate const_cstr_fork;

Example

 #[macro_use] extern crate const_cstr_fork;
 // Just for the `libc::c_char` type alias.
 extern crate libc;
     
 use std::ffi::CStr;

 const_cstr! {
     HELLO_CSTR = "Hello, world!";

     // Multiple declarations can be made with one invocation.
     // GOODNIGHT_CSTR = "Goodnight, sun!";

     // But only with the same visibility:
     // pub GOODNIGHT_CSTR = "Goodnight, sun!";
     // ^~~ Error: expected identifier, found `pub` 
 }

 // Imagine this is an `extern "C"` function linked from some other lib.
 unsafe fn print_c_string(cstr: *const libc::c_char) {
     println!("{}", CStr::from_ptr(cstr).to_str().unwrap());
 }

 fn main() {
     // When just passed a literal, returns an rvalue instead.
     let goodnight_cstr = const_cstr!("Goodnight, sun!");

     unsafe {
         print_c_string(HELLO_CSTR.as_ptr());
         print_c_string(goodnight_cstr.as_ptr());
     }
 }

Prints:

Hello, world!
Goodnight, sun!

License

Licensed under either of

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~43KB