diff options
Diffstat (limited to 'safe_libc/src/string.rs')
-rw-r--r-- | safe_libc/src/string.rs | 23 |
1 files changed, 16 insertions, 7 deletions
diff --git a/safe_libc/src/string.rs b/safe_libc/src/string.rs index 8f973ad..53f8f87 100644 --- a/safe_libc/src/string.rs +++ b/safe_libc/src/string.rs @@ -1,12 +1,11 @@ -use crate as libc; -use crate::util; -use crate::boxed::CBox; +use crate::{self as libc, util, boxed::CBox}; use core::slice; use core::ops::{Deref, DerefMut}; //pub struct FromBytesWithNulError {} +#[repr(transparent)] pub struct CStr { inner: libc::c_char } impl CStr { @@ -43,7 +42,7 @@ impl CStr { #[inline] pub fn len(&self) -> usize { - unsafe { libc::strlen(self.as_ptr()) as usize } + unsafe { libc::strlen(self.as_ptr()) } } #[inline] @@ -57,7 +56,7 @@ impl CStr { } #[inline] - pub fn as_bytes(&self) -> &[u8] { + pub fn to_bytes(&self) -> &[u8] { unsafe { slice::from_raw_parts( self.as_ptr().cast(), self.len(), @@ -65,7 +64,7 @@ impl CStr { } #[inline] - pub fn as_mut_bytes(&mut self) -> &mut [u8] { + pub fn to_mut_bytes(&mut self) -> &mut [u8] { unsafe { slice::from_raw_parts_mut( self.as_mut_ptr().cast(), self.len(), @@ -73,6 +72,16 @@ impl CStr { } #[inline] + pub fn to_str(&self) -> Result<&str, core::str::Utf8Error> { + core::str::from_utf8(self.to_bytes()) + } + + #[inline] + pub fn to_mut_str(&mut self) -> Result<&mut str, core::str::Utf8Error> { + core::str::from_utf8_mut(self.to_mut_bytes()) + } + + #[inline] pub fn to_owned(self: &CStr) -> CString { CString::from(self) } @@ -127,7 +136,7 @@ impl From<&[u8]> for CString { CString::from_raw_unchecked( util::must_succeed(libc::strndup( s.as_ptr().cast(), - s.len() as libc::size_t, + s.len(), )) ) } |