summaryrefslogtreecommitdiffstats
path: root/safe_libc/src/errno.rs
diff options
context:
space:
mode:
Diffstat (limited to 'safe_libc/src/errno.rs')
-rw-r--r--safe_libc/src/errno.rs29
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),
+ }
+ }
+}