From 1891c3e1aa83c92c8bd644541d13441f30b55c0c Mon Sep 17 00:00:00 2001 From: emma Date: Mon, 18 Mar 2024 21:30:43 -0600 Subject: [PATCH] strerror(3): created strerror() method --- src/strerror.rs | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/strerror.rs b/src/strerror.rs index e5a2a95..e306e7a 100644 --- a/src/strerror.rs +++ b/src/strerror.rs @@ -9,19 +9,23 @@ use std::ffi::{ c_int, c_char, CStr }; -/* binding to strerror(3p) */ -extern "C" { fn strerror(errnum: c_int) -> *mut c_char; } +pub trait StrError { fn strerror(&self) -> String; } -/* wrapper function for use in Rust */ -pub fn raw_message(err: std::io::Error) -> String { - /* Get the raw OS error. If it’s None, what the hell is going on‽ */ - let errno = err.raw_os_error().unwrap_or(0) as c_int; +impl StrError for std::io::Error { + /* wrapper function for use in Rust */ + fn strerror(&self) -> String { + /* Get the raw OS error. If it’s None, what the hell is going on‽ */ + let errno = self.raw_os_error().unwrap_or(0) as c_int; - /* Get a CStr from the error message so that it’s referenced and then - * convert it to an owned value. If the string is not valid UTF-8, return - * that error instead. */ - match unsafe { CStr::from_ptr(strerror(errno)) }.to_str() { - Ok(s) => s.to_owned(), // yay!! :D - Err(e) => e.to_string(), // awww :( + /* Get a CStr from the error message so that it’s referenced and then + * convert it to an owned value. If the string is not valid UTF-8, + * return that error instead. */ + match unsafe { CStr::from_ptr(strerror(errno)) }.to_str() { + Ok(s) => s.to_owned(), // yay!! :D + Err(e) => e.to_string(), // awww :( + } } } + +/* binding to strerror(3p) */ +extern "C" { fn strerror(errnum: c_int) -> *mut c_char; }