From 1867de581fa5467e2f85788dbcd227baa4f9da07 Mon Sep 17 00:00:00 2001 From: ltdk Date: Sun, 13 Nov 2022 04:09:20 -0500 Subject: [PATCH] Add in as_c_str and AsRef impl (contested in original ACP) --- library/core/src/ffi/c_str.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/library/core/src/ffi/c_str.rs b/library/core/src/ffi/c_str.rs index aea04e59c7ee5..8e7288068b0cc 100644 --- a/library/core/src/ffi/c_str.rs +++ b/library/core/src/ffi/c_str.rs @@ -731,6 +731,23 @@ impl<'a> CStrBytes<'a> { // the nul terminator. unsafe { *self.ptr.as_ref() == 0 } } + + /// Returns the remainder of the string as a slice. + #[unstable(feature = "cstr_bytes", issue = "none")] + #[inline] + pub fn as_c_str(&self) -> &'a CStr { + // SAFETY: We start with a valid C string and never increment beyond the + // nul terminator, retaining a valid C string, even if it's empty. + unsafe { CStr::from_ptr(self.ptr.as_ptr() as *mut u8 as *const c_char) } + } +} + +#[unstable(feature = "cstr_bytes", issue = "none")] +impl AsRef for CStrBytes<'_> { + #[inline] + fn as_ref(&self) -> &CStr { + self.as_c_str() + } } #[unstable(feature = "cstr_bytes", issue = "none")]