From 8cf47c7ec6356a1d0a9cd53ffa67c424d2e800c7 Mon Sep 17 00:00:00 2001 From: Ivan Molodetskikh Date: Wed, 28 Jun 2017 11:53:24 +0300 Subject: [PATCH] format/pixel: implement FromStr for Pixel --- src/util/format/pixel.rs | 59 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/src/util/format/pixel.rs b/src/util/format/pixel.rs index d0cc5a9..0d95d18 100644 --- a/src/util/format/pixel.rs +++ b/src/util/format/pixel.rs @@ -1,5 +1,7 @@ -use std::ffi::CStr; -use std::str::from_utf8_unchecked; +use std::error; +use std::ffi::{CStr, CString, NulError}; +use std::fmt; +use std::str::{FromStr, from_utf8_unchecked}; use ffi::*; @@ -859,3 +861,56 @@ impl Into for Pixel { } } } + +#[derive(Debug)] +pub enum ParsePixelError { + NulError(NulError), + UnknownFormat, +} + +impl fmt::Display for ParsePixelError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match *self { + ParsePixelError::NulError(ref e) => e.fmt(f), + ParsePixelError::UnknownFormat => write!(f, "unknown pixel format") + } + } +} + +impl error::Error for ParsePixelError { + fn description(&self) -> &str { + match *self { + ParsePixelError::NulError(ref e) => e.description(), + ParsePixelError::UnknownFormat => "unknown pixel format" + } + } + + fn cause(&self) -> Option<&error::Error> { + match *self { + ParsePixelError::NulError(ref e) => Some(e), + ParsePixelError::UnknownFormat => None + } + } +} + +impl From for ParsePixelError { + fn from(x: NulError) -> ParsePixelError { + ParsePixelError::NulError(x) + } +} + +impl FromStr for Pixel { + type Err = ParsePixelError; + + #[inline(always)] + fn from_str(s: &str) -> Result { + let cstring = CString::new(s)?; + let format = unsafe { av_get_pix_fmt(cstring.as_ptr()) }.into(); + + if format == Pixel::None { + Err(ParsePixelError::UnknownFormat) + } else { + Ok(format) + } + } +}