liveBook · Manning

LitInt

As explained in Write Powerful Rust Macros

LitInt is syn's syntax structure representing a Rust integer literal together with its source span.

LitInt is syn’s parser type for Rust integer literals. It reads numeric property values such as memory and timeout, then supports conversion into application types such as u16. section 9.3.2

A typical LitInt workflow has three steps:

  • Parse the numeric token as LitInt so non-numeric input produces a syntax error. section 9.3.2
  • Convert the literal text to u16, allowing the Rust type to reject values outside the representable range. section 9.3.2
  • Add domain-specific checks separately when the syntax permits values that the application should reject, such as a timeout above 900. section 9.3.2

Parsing a numeric property

A parser can read a custom keyword, require an equals sign, and parse the value as LitInt: `let value = input.parse().map(|v: LitInt| v.to_string().parse())??;`. Invalid text such as `mem "yes"` produces an expected-integer-literal error, while a negative value fails when converted to u16. section 9.4.2 section 9.3.2

Listing 9.15 The generic parse_number helper
fn parse_number<T>(input: ParseStream, error_message: &str)
                   -> Result<u16, syn::Error>
                    where T: Parse {             #1
    let _ = input.parse::<T>()               #2
        .expect("we just checked for this token");
    let _: Token!(=) = input.parse()
        .map_err(|_| syn::Error::new(
            input.span(),
            "prop name and value should be separated by =")
        )?;
    let value = input.parse()
        .map(|v: LitInt| v.to_string()
            .parse()
            .map_err(|_| {
                syn::Error::new(
                    v.span(),
                    error_message,
                )
            })
        )??;
    Ok(value)
}

Inspect the generic helper that parses custom keywords, consumes `=`, converts LitInt to u16, and reports errors at the literal’s span. section 9.4.2

How Write Powerful Rust Macros covers it

How deep it goes
Explains parsing, string conversion, u16 conversion, and supplemental bounds checks, but defers complete domain validation.
Examples
Uses memory and timeout properties, valid values such as 1024 and 15, and invalid string or negative inputs.
What it assumes
Assumes familiarity with syn parsing and ParseStream while demonstrating integer-literal validation from the parser boundary.
What you can do after
Apply it via syn to parse integer literals, convert them to u16, and produce focused compile-time diagnostics.
How it connects
Connects LitInt with Parse, ParseStream, syn::Error, custom keywords, source spans, and u16.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.