]> git.proxmox.com Git - proxmox.git/commitdiff
lang: prepare c_str for const fns with 1.56
authorWolfgang Bumiller <w.bumiller@proxmox.com>
Tue, 12 Oct 2021 12:29:01 +0000 (14:29 +0200)
committerWolfgang Bumiller <w.bumiller@proxmox.com>
Tue, 12 Oct 2021 12:29:03 +0000 (14:29 +0200)
provides an api compatible const-fn-compatible c_str
alternative working on 1.56

Signed-off-by: Wolfgang Bumiller <w.bumiller@proxmox.com>
proxmox-lang/src/lib.rs

index 31430c440e3a21f1c095cb8934d2576c1dbf0bbb..06e0b319efa66e3c36213762bf6331c2e6a9e1fa 100644 (file)
@@ -108,3 +108,31 @@ macro_rules! c_str {
         unsafe { ::std::ffi::CStr::from_bytes_with_nul_unchecked(bytes.as_bytes()) }
     }};
 }
+
+/*
+// With rust 1.56 we can enable the `c_str!()` macro for const fns:
+
+#[doc(hidden)]
+#[allow(unconditional_panic)]
+pub const fn illegal_c_string() {
+    [][0]
+}
+
+/// Assert that a static byte slice is a valid C string (has no zeros except at the very end),
+/// and return it as a `&'static CStr`.
+pub const fn checked_c_str(bytes: &'static [u8]) -> &'static std::ffi::CStr {
+    let mut i = 0;
+    while i < bytes.len() - 1 {
+        if bytes[i] == 0 {
+            illegal_c_string();
+        }
+        i += 1;
+    }
+    unsafe { std::mem::transmute::<_, &'static std::ffi::CStr>(bytes) }
+}
+
+#[macro_export]
+macro_rules! c_str {
+    ($data:expr) => { $crate::checked_c_str(concat!($data, "\0")) };
+}
+*/