Crate bparse

Source
Expand description

§Overview

Parsing usually involves going through a sequence of items and branching off based on the element that was seen. This crate simplifies the task of recognizing complex patterns in a slices. It works with any type of slice.

It is made up of three parts:

  1. The Pattern trait: represents the pattern to be recognized.
  2. A list of common functions and combinators for composing Patterns together.
  3. The SliceReader struct; a Cursor-like wrapper around an input slice that uses patterns to advance its position.

§Example

Recognizing JSON numbers can get tricky. The spec allows for numbers like 12, -398.42, and even 12.4e-3. Here we incrementally build up a pattern called number that can recognizes all JSON number forms.

use bparse::{SliceReader, Pattern, range, at_least, optional, byte::oneof};

let sign = optional(oneof(b"-+"));
let onenine = range(b'1', b'9');
let digit = "0".or(onenine);
let digits = at_least(1, digit);
let fraction = optional(".".then(digits));
let exponent = optional("E".then(sign).then(digits).or("e".then(sign).then(digits)));
let integer = onenine
    .then(digits)
    .or("-".then(onenine).then(digits))
    .or("-".then(digit))
    .or(digit);
let number = integer.then(fraction).then(exponent);

let input = b"234||344.5||0.43e12";

let mut reader = SliceReader::new(input);

let Some(b"234") = reader.parse(number) else {
    panic!();
};

assert!(reader.accept("||"));

let Some(b"344.5") = reader.parse(number) else {
    panic!();
};

assert!(reader.accept("||"));

let Some(b"0.43e12") = reader.parse(number) else {
    panic!();
};

assert!(reader.eof());

Modules§

byte
Patterns that only match against byte slices

Structs§

Choice
See Pattern::or
ElementRange
See range()
Not
See not
One
See one
Prefix
See prefix
Repetition
Exppresses pattern repetition.
Sequence
See Pattern::then
SliceReader
Wraps a slice of elements of type T with a movable cursor.

Traits§

Pattern
Expresses that the implementing type may be used to match a slice with elements of type T.

Functions§

any
Returns a new pattern that matches as many repetitions as possible of the given pattern, including 0.
at_least
Returns a new pattern that matches at least n repetitions of pattern.
at_most
Returns a new pattern that matches at most n repetitions of pattern.
between
Returns a new pattern that matches between lo and hi repetitions of pattern.
count
Returns a new pattern that matches exactly n repetitions of pattern.
not
Returns a new pattern that matches only if pattern does not match
one
Returns a new pattern that always matches the next element in the input if it exists.
optional
Returns a new pattern that matches 0 or 1 repetitions of pattern
prefix
Returns a new pattern that will match if slice is a prefix of the input.
range
Returns a new pattern that will match an element in the closed interval [lo, hi]