1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#![allow(unsafe_code)]
pub struct ToCStr<T>(pub T);
impl ToCStr<&str> {
const fn check_nul(&self) {
let bytes = self.0.as_bytes();
let mut i = 0;
while i < bytes.len() {
constfn_assert!(bytes[i] != 0);
i += 1;
}
}
pub const fn output_len(&self) -> usize {
self.check_nul();
self.0.as_bytes().len() + 1
}
pub const fn const_eval<const N: usize>(&self) -> [u8; N] {
let mut buf = [0; N];
let mut pos = 0;
let bytes = self.0.as_bytes();
let mut i = 0;
while i < bytes.len() {
constfn_assert!(bytes[i] != 0);
buf[pos] = bytes[i];
pos += 1;
i += 1;
}
pos += 1;
constfn_assert!(pos == N);
buf
}
}
#[macro_export]
macro_rules! raw_cstr {
($s: expr) => {{
const OUTPUT_LEN: ::core::primitive::usize = $crate::__ctfe::ToCStr($s).output_len();
const OUTPUT_BUF: [u8; OUTPUT_LEN] = $crate::__ctfe::ToCStr($s).const_eval();
const OUTPUT: *const ::std::os::raw::c_char = OUTPUT_BUF.as_ptr().cast();
OUTPUT
}};
}
#[test]
fn test_raw_cstr() {
const FMT: &str = "%d\n";
let fmt = raw_cstr!(FMT);
let len = FMT.len() + 1;
let bytes: &[u8] = unsafe { core::slice::from_raw_parts(fmt.cast(), len) };
assert_eq!(bytes, b"%d\n\0");
}