cstringify/
lib.rs

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.
4
5//! This crate contains the [`cstringify`] macro for making a `&'static CStr` out of a path.
6
7#![deny(missing_docs)]
8
9/// 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.
16        unsafe {
17            ::core::ffi::CStr::from_bytes_with_nul_unchecked(
18                concat!(stringify!($x), "\0").as_bytes(),
19            )
20        }
21    };
22}
23
24#[cfg(test)]
25mod tests {
26    use super::cstringify;
27    use std::ffi;
28
29    #[test]
30    fn cstringify_simple_ident() {
31        let expected = ffi::CString::new("foo").unwrap();
32        let expected = expected.as_c_str();
33        let result = cstringify!(foo);
34
35        assert_eq!(expected, result);
36    }
37
38    #[test]
39    fn cstringify_non_ascii_ident() {
40        let expected = ffi::CString::new("例").unwrap();
41        let expected = expected.as_c_str();
42        let result = cstringify!(例);
43
44        assert_eq!(expected, result);
45    }
46
47    #[test]
48    fn compatible_with_const() {
49        const _TEST_STRING: &'static ffi::CStr = cstringify!(foo);
50    }
51}