From eef3e9c55685623fe4373600682ffb5e3764c3e6 Mon Sep 17 00:00:00 2001 From: meh Date: Thu, 7 May 2015 04:32:32 +0200 Subject: [PATCH] util/error: add error handling --- src/lib.rs | 1 + src/util/error.rs | 50 +++++++++++++++++++++++++++++++++++++++++++++++ src/util/mod.rs | 2 ++ 3 files changed, 53 insertions(+) create mode 100644 src/util/error.rs diff --git a/src/lib.rs b/src/lib.rs index 5be08db..385faa7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,3 +5,4 @@ extern crate ffmpeg_sys as ffi; #[macro_use] extern crate bitflags; pub mod util; +pub use util::error::Error; diff --git a/src/util/error.rs b/src/util/error.rs new file mode 100644 index 0000000..f60a70e --- /dev/null +++ b/src/util/error.rs @@ -0,0 +1,50 @@ +use ffi::*; +use std::error; +use std::fmt; +use std::cell::RefCell; +use libc::c_int; +use std::ffi::CStr; +use std::str::from_utf8_unchecked; + +pub struct Error { + code: c_int, + desc: RefCell>, +} + +impl Error { + pub fn new(code: c_int) -> Self { + Error { code: code, desc: RefCell::new(None) } + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + f.write_str(error::Error::description(self)) + } +} + +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { + try!(f.write_str("ffmpeg::Error(")); + try!(f.write_str(&format!("{}: ", AVUNERROR(self.code)))); + try!(fmt::Display::fmt(self, f)); + f.write_str(")") + } +} + +impl error::Error for Error { + fn description(&self) -> &str { + unsafe { + let mut desc = self.desc.borrow_mut(); + + if let None = *desc { + let mut buf = [0i8; AV_ERROR_MAX_STRING_SIZE as usize]; + av_strerror(self.code, buf.as_mut_ptr(), AV_ERROR_MAX_STRING_SIZE); + + *desc = Some(buf); + } + + from_utf8_unchecked(CStr::from_ptr(desc.unwrap().as_ptr()).to_bytes()) + } + } +} diff --git a/src/util/mod.rs b/src/util/mod.rs index 1a907d8..4b7ef5a 100644 --- a/src/util/mod.rs +++ b/src/util/mod.rs @@ -1,3 +1,5 @@ +pub mod error; + use std::ffi::CStr; use std::str::from_utf8_unchecked;