netdoc: Relax error types that can be used when parsing.

This commit is contained in:
Nick Mathewson 2020-05-15 14:01:50 -04:00
parent 0427abcee2
commit c1d6a74756
2 changed files with 34 additions and 7 deletions

View File

@ -260,4 +260,28 @@ impl Error {
}
self
}
/// Return a new error based on this one, with the position (if
/// replaced by 'p' if it had no position before.
pub fn or_at_pos(mut self, p: Pos) -> Error {
if let Some(mypos) = self.pos_mut() {
if *mypos == Pos::None {
*mypos = p;
}
}
self
}
}
macro_rules! derive_from_err{
{ $etype:ty } => {
impl From<$etype> for Error {
fn from(e: $etype) -> Error {
Error::BadArgument(Pos::None, e.to_string())
}
}
}
}
derive_from_err! {std::num::ParseIntError}
derive_from_err! {std::net::AddrParseError}

View File

@ -279,13 +279,16 @@ impl<'a> Item<'a> {
/// Returns Ok(None) if the argument doesn't exist.
pub fn parse_optional_arg<V: FromStr>(&self, idx: usize) -> Result<Option<V>>
where
<V as FromStr>::Err: std::error::Error,
Error: From<V::Err>,
{
match self.get_arg(idx) {
None => Ok(None),
Some(s) => match s.parse() {
Ok(r) => Ok(Some(r)),
Err(e) => Err(Error::BadArgument(Pos::at(s), e.to_string())),
Err(e) => {
let e: Error = e.into();
Err(e.or_at_pos(Pos::at(s)))
}
},
}
}
@ -295,7 +298,7 @@ impl<'a> Item<'a> {
/// Return an error if the argument doesn't exist.
pub fn parse_arg<V: FromStr>(&self, idx: usize) -> Result<V>
where
<V as FromStr>::Err: std::error::Error,
Error: From<V::Err>,
{
match self.parse_optional_arg(idx) {
Ok(Some(v)) => Ok(v),
@ -389,7 +392,7 @@ impl<'a, 'b> MaybeItem<'a, 'b> {
}
pub fn parse_arg<V: FromStr>(&self, idx: usize) -> Result<Option<V>>
where
<V as FromStr>::Err: std::error::Error,
Error: From<V::Err>,
{
match self.0 {
Some(item) => item.parse_arg(idx).map(Some),
@ -399,7 +402,7 @@ impl<'a, 'b> MaybeItem<'a, 'b> {
#[allow(dead_code)]
pub fn parse_optional_arg<V: FromStr>(&self, idx: usize) -> Result<Option<V>>
where
<V as FromStr>::Err: std::error::Error,
Error: From<V::Err>,
{
match self.0 {
Some(item) => item.parse_optional_arg(idx),
@ -411,9 +414,9 @@ impl<'a, 'b> MaybeItem<'a, 'b> {
self.0.map(|item| item.args_as_str())
}
#[allow(dead_code)]
pub fn parse_args_as_str<V>(&self) -> Result<Option<V>>
pub fn parse_args_as_str<V: FromStr>(&self) -> Result<Option<V>>
where
V: FromStr<Err = Error>,
Error: From<V::Err>,
{
match self.0 {
Some(item) => Ok(Some(item.args_as_str().parse::<V>()?)),