Skip to content

Commit a70b32c

Browse files
committed
Add map functions for Error<> and Info<> ranges. (Marwes#86)
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`.
1 parent 6f2cec6 commit a70b32c

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/primitives.rs

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,18 @@ pub enum Info<T, R> {
5656
Borrowed(&'static str),
5757
}
5858

59+
impl<T, R> Info<T, R> {
60+
pub fn map_range<F, S>(self, f: F) -> Info<T, S> where F: FnOnce(R) -> S {
61+
use self::Info::*;
62+
match self {
63+
Token(t) => Token(t),
64+
Range(r) => Range(f(r)),
65+
Owned(s) => Owned(s),
66+
Borrowed(x) => Borrowed(x),
67+
}
68+
}
69+
}
70+
5971
impl<T: PartialEq, R: PartialEq> PartialEq for Info<T, R> {
6072
fn eq(&self, other: &Info<T, R>) -> bool {
6173
match (self, other) {
@@ -110,6 +122,18 @@ pub enum Error<T, R> {
110122
Other(Box<StdError + Send + Sync>),
111123
}
112124

125+
impl<T, R> Error<T, R> {
126+
pub fn map_err_range<F, S>(self, f: F) -> Error<T, S> where F: FnOnce(R) -> S {
127+
use self::Error::*;
128+
match self {
129+
Unexpected(x) => Unexpected(x.map_range(f)),
130+
Expected(x) => Expected(x.map_range(f)),
131+
Message(x) => Message(x.map_range(f)),
132+
Other(x) => Other(x),
133+
}
134+
}
135+
}
136+
113137
impl<T: PartialEq, R: PartialEq> PartialEq for Error<T, R> {
114138
fn eq(&self, other: &Error<T, R>) -> bool {
115139
match (self, other) {
@@ -404,6 +428,18 @@ impl<S: StreamOnce> ParseError<S> {
404428
}
405429
}
406430
}
431+
432+
pub fn map_err_range<F, R, T>(self, f: F) -> ParseError<T>
433+
where R: Clone + PartialEq,
434+
F: Fn(S::Range) -> R,
435+
T: StreamOnce<Item = S::Item, Range = R, Position = S::Position> {
436+
ParseError::from_errors(
437+
self.position,
438+
self.errors
439+
.into_iter()
440+
.map(|e: Error<S::Item, S::Range>| e.map_err_range(&f))
441+
.collect())
442+
}
407443
}
408444

409445
impl<'s> ParseError<&'s str> {

0 commit comments

Comments
 (0)