KeyTree
is an elegant markup language designed to convert human readable information into Rust
data-structures. It is designed to be fast, to reduce cognitive load and to be easy to
implement for one's own types. It has no dependencies on other crates and so is fast to
compile. The format looks like
text
hobbit:
name: Frodo Baggins
age: 98
friends:
hobbit:
name: Bilbo Baggins
age: 176
hobbit:
name: Samwise Gamgee
age: 66
so data can be recursive. Also, it is easy to refer to a set of data using a path such as
hobbit::friends::hobbit
refers to a collection of two hobbits.
This library does not follow the standard Rust error handling pattern. If there is a parsing error it will crash or if there is an error in converting a value into a Rust type it will crash (with a nice error message). If you don't want this to happen, you will need to run this in its own thread/process.
Indentation has meaning and is 4 spaces, relative to the top key. Since indenting is relative to the top key, then you can neatly align strings embedded in code.
Each line can be empty, have whitespace only, be a comment, be a key, or be a key/value pair.
There are keys and values. Key/Value pairs look like
text
name: Frodo
are used for struct
fields and enum
variants.
Keys refer to child keys or child key/value pairs indented on lines under it, for example
text
hobbit:
name: Frodo
hobbit refers to the name of the struct or enum. In this way, the data maps simply to Rust
data-structures.
test
hobbit:
name: Frodo
name: Bilbo
is a collection of hobbits.
Keys must not include but must be followed by a colon :
.
Values are all characters between the combination of ':' and whitespace and the end of the line. The value is trimmed of whitespace at both ends.
Comments require //
at the start of the line. For example
text
// comment
hobbit:
name: "Frodo"
Into
from KeyTree
into Rust types is automatically implemented for Vec<T>
, Option<T>
and basic Rust types. KeyTree
text can be automatically converted to these data types, making
use of type inference. The at()
function returns an iterator over KeyTree
types that can be
used to implement Into
for your own types. The following example should cover 90 percent of
use cases,
```rust use keytree::KeyTree; use keytree::parser::KeyTreeBuilder;
struct Hobbit {
name: String,
age: u32,
friends: Vec
impl<'a> Into
fn main() { let s = r#" hobbit: name: Frodo Baggins age: 98 friends: hobbit: name: Bilbo Baggins age: 176 hobbit: name: Samwise Gamgee age: 66 nick: Sam"#;
let core = KeyTreeBuilder::parse(s);
let hobbit: Hobbit = KeyTree::from_core(&core).into();
dbg!(&hobbit);
} ```