diff options
author | Matthias Schiffer <mschiffer@universe-factory.net> | 2020-04-13 02:13:58 +0200 |
---|---|---|
committer | Matthias Schiffer <mschiffer@universe-factory.net> | 2020-04-13 02:13:58 +0200 |
commit | 5b449f4e1e43bc59109da5a37edf5ec911d3df8e (patch) | |
tree | 46968e5619a1088f131f532a5d78e8ff4d033325 /safe_libc/src/string.rs | |
parent | fff906a78ba545e77d087a82711b30bcc8e0d0c5 (diff) | |
download | neco-5b449f4e1e43bc59109da5a37edf5ec911d3df8e.tar neco-5b449f4e1e43bc59109da5a37edf5ec911d3df8e.zip |
IO, error handling
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(), )) ) } |