pest_consume/advanced_features/user_data.rs
1//! ## Passing user data through the parser
2//!
3//! Sometimes, you may want to pass some data to the consuming methods.
4//! You could want access to configuration data, or to a store for
5//! [string interning](https://en.wikipedia.org/wiki/String_interning).
6//!
7//! This is easy to do: by using [`Parser::parse_with_userdata`] instead of [`Parser::parse`],
8//! you can provide some data that will be stored in the returned [`Nodes`] value, and accessible at any point
9//! during parsing via [`Node::user_data`].
10//!
11//! The type of the user data is the second type parameter in the types of `Node<'i, Rule, Data>` and `Nodes<'i, Rule, Data>`.
12//! The data needs to be `Clone`, and will be cloned often so it should be cheap to clone.
13//! A common usage is to have this data be a reference, which are free to clone.
14//!
15//! If you need mutable access to some data, use [`Cell`] or [`RefCell`].
16//!
17//! ```ignore
18//! struct AppSettings { ... }
19//!
20//! // We changed the type alias to include the type of the user data.
21//! type Node<'i, 'a> = pest_consume::Node<'i, Rule, &'a AppSettings>;
22//!
23//! fn parse_with_settings(
24//! input_str: &str,
25//! settings: &AppSettings
26//! ) -> Result<Vec<Vec<f64>>> {
27//! // Parse the input into `Nodes`, passing the provided settings along
28//! let inputs = CSVParser::parse_with_userdata(
29//! Rule::file,
30//! input_str,
31//! settings
32//! )?;
33//! let input = inputs.single()?;
34//! CSVParser::file(input)
35//! }
36//!
37//! #[pest_consume::parser]
38//! impl CSVParser {
39//! fn field(input: Node) -> Result<f64> {
40//! // The settings can be retrieved from any Node.
41//! let settings = input.user_data();
42//! if settings.do_the_thing {
43//! ...
44//! }
45//! ...
46//! }
47//! ...
48//! }
49//! ```
50//!
51//! [`Nodes`]: struct.Nodes.html
52//! [`Node::user_data`]: struct.Node.html#method.user_data
53//! [`Parser::parse`]: trait.Parser.html#method.parse
54//! [`Parser::parse_with_userdata`]: trait.Parser.html#method.parse_with_userdata
55//! [`Cell`]: https://doc.rust-lang.org/std/cell/struct.Cell.html
56//! [`RefCell`]: https://doc.rust-lang.org/std/cell/struct.RefCell.html