pub fn one_of<L: ParserList>(options: L) -> OneOf<L>
Expand description
Attempt to parse using a list of parsers.
Similar to Parser::or
, each parser will be tried in order until one succeeds. If no parsers
succeed, the error from the parser furthest into the input is returned.
Prefer parser::literal_map
if all the parsers are string literals.
§Examples
#[derive(Debug, PartialEq)]
enum Value {
Unsigned8(u8),
Unsigned32(u32),
Signed8(i8),
Signed32(i32),
}
let parser = parser::one_of((
parser::u8().map(Value::Unsigned8),
parser::u32().map(Value::Unsigned32),
parser::i8().map(Value::Signed8),
parser::i32().map(Value::Signed32),
));
assert_eq!(
parser.parse_complete("31").unwrap(),
Value::Unsigned8(31),
);
assert_eq!(
parser.parse_complete("4294967295").unwrap(),
Value::Unsigned32(4294967295),
);
assert_eq!(
parser.parse_complete("-1").unwrap(),
Value::Signed8(-1)
);
assert_eq!(
parser.parse_complete("-2147483648").unwrap(),
Value::Signed32(-2147483648)
);
assert_eq!(
parser.parse(b"not a number").unwrap_err().0,
ParseError::Expected("unsigned integer")
);
assert_eq!(
parser.parse(b"-4294967295").unwrap_err().0,
ParseError::NumberTooSmall(-2147483648)
);