Derive Macro Parse

Source
#[derive(Parse)]
{
    // Attributes available to this derive:
    #[parse]
}
Expand description

Derive a default JSON parser for a unit value, struct or enum.

§Examples

You can derive a parser for a struct with fields that implement the Parse trait:

#[derive(Parse, Schema, Debug, Clone, PartialEq)]
struct Person {
    name: String,
    age: u32,
}

let parser = Person::new_parser();
let state = parser.create_parser_state();
let person = parser.parse(&state, b"{ \"name\": \"John\", \"age\": 30 } ").unwrap().unwrap_finished();
assert_eq!(person.name, "John");
assert_eq!(person.age, 30);

Or an enum with unit variants:

#[derive(Parse, Schema, Debug, Clone, PartialEq)]
enum Color {
    Red,
    Blue,
    Green,
}

let parser = Color::new_parser();
let state = parser.create_parser_state();
let color = parser.parse(&state, b"\"Red\" ").unwrap().unwrap_finished();
assert_eq!(color, Color::Red);

You can even derive Parse for an enum with data variants:

#[derive(Parse, Schema, Debug, Clone, PartialEq)]
enum Action {
    Search { query: String },
    Quit,
}

let parser = Action::new_parser();
let state = parser.create_parser_state();
let action = parser.parse(&state, b"{ \"type\": \"Search\", \"data\": { \"query\": \"my query\" } } ").unwrap().unwrap_finished();
assert_eq!(action, Action::Search { query: "my query".to_string() });

§Attributes

The #[parse] attribute modifies the default behavior of the parser. It can be used in the following forms:

  • #[parse(rename = "name")] renames the field or type to name (defaults to the field name)
#[derive(Parse, Schema, Clone)]
struct Person {
    #[parse(rename = "full name")]
    name: String,
    age: u32,
}

#[derive(Parse, Schema, Clone)]
enum Color {
    #[parse(rename = "red")]
    Red,
    Blue,
    Green,
}
  • #[parse(with = expression)] uses the expression to parse the field (defaults to the parser provided by the Parse implementation for the field type)
#[derive(Parse, Schema, Clone)]
struct Person {
    #[parse(with = StringParser::new(1..=10))]
    name: String,
    age: u32,
}
  • #[parse(tag = "tag")] changes the name of the tag for enum variants (defaults to “type”)
#[derive(Parse, Schema, Clone)]
#[parse(tag = "action")]
enum Action {
    Search { query: String },
    Quit,
}
  • #[parse(content = "content")] changes the name of the content for enum variants (defaults to “data”)
#[derive(Parse, Schema, Clone)]
#[parse(content = "arguments")]
enum Action {
    Search { query: String },
    Quit,
}