Skip to content

Commit

Permalink
Add map functions for Error<> and Info<> ranges. (Marwes#86)
Browse files Browse the repository at this point in the history
It's possible to `map_err_range` for `ParseResult<>` too, but it's
awkward because the output type needs to be a compatible `StreamOnce`.
As suggested in
Marwes#86 (comment),
it's probably best to either change the parse result type entirely, or
wait for rust-lang/rust#21903.

This at least helps consumers convert `ParseError<>` into something
that can implement `std::fmt::Display`.
  • Loading branch information
ncalexan committed Feb 17, 2017
1 parent 6f2cec6 commit a70b32c
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/primitives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,18 @@ pub enum Info<T, R> {
Borrowed(&'static str),
}

impl<T, R> Info<T, R> {
pub fn map_range<F, S>(self, f: F) -> Info<T, S> where F: FnOnce(R) -> S {
use self::Info::*;
match self {
Token(t) => Token(t),
Range(r) => Range(f(r)),
Owned(s) => Owned(s),
Borrowed(x) => Borrowed(x),
}
}
}

impl<T: PartialEq, R: PartialEq> PartialEq for Info<T, R> {
fn eq(&self, other: &Info<T, R>) -> bool {
match (self, other) {
Expand Down Expand Up @@ -110,6 +122,18 @@ pub enum Error<T, R> {
Other(Box<StdError + Send + Sync>),
}

impl<T, R> Error<T, R> {
pub fn map_err_range<F, S>(self, f: F) -> Error<T, S> where F: FnOnce(R) -> S {
use self::Error::*;
match self {
Unexpected(x) => Unexpected(x.map_range(f)),
Expected(x) => Expected(x.map_range(f)),
Message(x) => Message(x.map_range(f)),
Other(x) => Other(x),
}
}
}

impl<T: PartialEq, R: PartialEq> PartialEq for Error<T, R> {
fn eq(&self, other: &Error<T, R>) -> bool {
match (self, other) {
Expand Down Expand Up @@ -404,6 +428,18 @@ impl<S: StreamOnce> ParseError<S> {
}
}
}

pub fn map_err_range<F, R, T>(self, f: F) -> ParseError<T>
where R: Clone + PartialEq,
F: Fn(S::Range) -> R,
T: StreamOnce<Item = S::Item, Range = R, Position = S::Position> {
ParseError::from_errors(
self.position,
self.errors
.into_iter()
.map(|e: Error<S::Item, S::Range>| e.map_err_range(&f))
.collect())
}
}

impl<'s> ParseError<&'s str> {
Expand Down

0 comments on commit a70b32c

Please sign in to comment.