bparse/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#![warn(missing_docs)]
//! ## 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.
//! 1. A list of common functions and combinators for composing `Patterns` together.
//! 1. The [`SliceReader`] struct; a [`Cursor`](std::io::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());
//! ```

mod pattern;
mod slice_reader;

pub use pattern::*;
pub use slice_reader::SliceReader;