We can save and load an RTree by serde. To use serde, we need to add feature serde to rstar.
cargo add rstar -F serde
In this tutorial, we use serde_json to do the (de)serialization.
cargo add serde_json
The dependencies in Cargo.toml
should look like this:
[dependencies]
rstar = { version = "0.12.0", features = ["serde"] }
serde_json = "1.0.131"
Now, we can use serde_json::to_string_pretty and serde_json::from_str to save and load an RTree.
use rstar::RTree;
fn main() {
let tree = RTree::bulk_load(vec![(0, 0), (1, 2), (8, 5)]);
let json = serde_json::to_string_pretty(&tree).unwrap();
println!("{}", json);
let tree2: RTree<(i32, i32)> = serde_json::from_str(&json).unwrap();
println!("Points in tree2:");
for point in &tree2 {
println!("{:?}", point);
}
}
Output:
{
"root": {
"children": [
{
"Leaf": [
0,
0
]
},
{
"Leaf": [
1,
2
]
},
{
"Leaf": [
8,
5
]
}
],
"envelope": {
"lower": [
0,
0
],
"upper": [
8,
5
]
}
},
"size": 3,
"_params": null
}
Points in tree2:
(8, 5)
(1, 2)
(0, 0)
➡️ Next: Custom Data Types
📘 Back: Table of contents