1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
45//! This crate contains the [`cstringify`] macro for making a `&'static CStr` out of a path.
67#![deny(missing_docs)]
89/// Creates a `&'static CStr` from a path.
10#[macro_export]
11macro_rules! cstringify {
12 ($x:path) => {
13// Safety: The concat!() adds a nul byte, and a Rust path cannot contain a nul byte.
14 // The latter is true because https://doc.rust-lang.org/reference/identifiers.html excludes
15 // Unicode control characters from identifiers, and U+0000 is a control character.
16unsafe {
17 ::core::ffi::CStr::from_bytes_with_nul_unchecked(
18concat!(stringify!($x), "\0").as_bytes(),
19 )
20 }
21 };
22}
2324#[cfg(test)]
25mod tests {
26use super::cstringify;
27use std::ffi;
2829#[test]
30fn cstringify_simple_ident() {
31let expected = ffi::CString::new("foo").unwrap();
32let expected = expected.as_c_str();
33let result = cstringify!(foo);
3435assert_eq!(expected, result);
36 }
3738#[test]
39fn cstringify_non_ascii_ident() {
40let expected = ffi::CString::new("例").unwrap();
41let expected = expected.as_c_str();
42let result = cstringify!(例);
4344assert_eq!(expected, result);
45 }
4647#[test]
48fn compatible_with_const() {
49const _TEST_STRING: &'static ffi::CStr = cstringify!(foo);
50 }
51}