Skip to content

Files

Latest commit

 

History

History
43 lines (35 loc) · 2.37 KB

custom_input_types.md

File metadata and controls

43 lines (35 loc) · 2.37 KB

Custom input types

While historically, nom has worked mainly on &[u8] and &str, it can actually use any type as input, as long as they follow a specific set of traits. Those traits were developed first to abstract away the differences between &[u8] and &str, but were then employed for more interesting types, like nom_locate, a wrapper type that can carry line and column information, or to parse a list of tokens.

Implementing a custom type

Let's assume we have an input type we'll call MyInput. MyInput is a sequence of MyItem type. The goal is to define nom parsers with this signature: MyInput -> IResult<MyInput, Output>.

fn parser(i: MyInput) -> IResult<MyInput, Output> {
    tag("test")(i)
}

Here are the traits we have to implement for MyInput:

trait usage
AsBytes Casts the input type to a byte slice
Compare Character comparison operations
ExtendInto Abstracts something which can extend an Extend
FindSubstring Look for a substring in self
FindToken Look for self in the given input stream
InputIter Common iteration operations on the input type
InputLength Calculate the input length
InputTake Slicing operations
InputTakeAtPosition Look for a specific token and split at its position
Offset Calculate the offset between slices
ParseTo Used to integrate &str's parse() method
Slice Slicing operations using ranges

Here are the traits we have to implement for MyItem:

trait usage
AsChar Transforms common types to a char for basic token parsing