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/errno.rs | |
parent | fff906a78ba545e77d087a82711b30bcc8e0d0c5 (diff) | |
download | neco-5b449f4e1e43bc59109da5a37edf5ec911d3df8e.tar neco-5b449f4e1e43bc59109da5a37edf5ec911d3df8e.zip |
IO, error handling
Diffstat (limited to 'safe_libc/src/errno.rs')
-rw-r--r-- | safe_libc/src/errno.rs | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/safe_libc/src/errno.rs b/safe_libc/src/errno.rs new file mode 100644 index 0000000..be944d1 --- /dev/null +++ b/safe_libc/src/errno.rs @@ -0,0 +1,29 @@ +use crate::string; + +use core::fmt; + +#[derive(Clone, Copy, Debug)] +#[repr(transparent)] +pub struct Errno(pub libc::c_int); + +#[inline] +pub fn errno() -> Errno { + unsafe { Errno(*libc::__errno_location()) } +} + +impl fmt::Display for Errno { + #[inline] + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let mut buf = [0u8; 1024]; + let cstr = unsafe { + if libc::strerror_r(self.0, buf.as_mut_ptr().cast(), buf.len()) != 0 { + return Err(fmt::Error); + } + string::CStr::from_bytes_with_nul_unchecked(&buf) + }; + match cstr.to_str() { + Err(_) => Err(fmt::Error), + Ok(s) => f.write_str(s), + } + } +} |