#tree #graph #memory #read-write #serialization #node #blocks

contigious-tree

将树图写入和读取到连续的内存块中

3个版本

0.1.2 2023年5月21日
0.1.1 2023年5月20日
0.1.0 2022年6月26日

#33 in #blocks

30 每月下载量

MIT 许可证

13KB
153

连续树

Docs Licence Crates.io

将树图写入和读取到连续的内存块中。这在您想要从内存映射文件中读取和加载非常大的树时非常有用。

关于

这是一个有用的树表示方法,适用于您想要序列化/反序列化树或非常快速查询树的情况。如果需要频繁更改树,请勿使用此crate。实现是泛型的,与节点关联的值类型及其二进制表示相关。

使用方法

考虑这个树

(1) root
 ├── (2)
 └── (3)
      └── (4)

写入

我们以深度优先的方式写入树。每个子树写入后,在父节点之前写入。

use contigious_tree::{TreeBuilder, LeI32};

/// Value type is a singend 32 Bit integer with a little endian representation.
type Node = LeI32;

// Any io::Write, will do for writing
let mut persistence = Vec::<u8>::new();

let mut builder = TreeBuilder::<Node, _>::new(&mut persistence);
// Build tree depth first. For each node pass a reference to the value and the number of preceding
// direct children.
builder.write_node(&4, 0).unwrap();
builder.write_node(&3, 1).unwrap();
builder.write_node(&2, 0).unwrap();
builder.write_node(&1, 2).unwrap();
builder.finish().unwrap();

读取

use contigious_tree::{TreeVec, LeI32};

let persistence: Vec<u8> = { /*... load tree from stoarge ...*/};

/// Value type is a singend 32 Bit integer with a little endian representation.
type Node = LeI32;

let tree = TreeVec::<Node>::new(persistence);
// Read value of tree root, and iterate over direct children
let (value, mut branches) = tree.read_node();
assert_eq!(1, value);
let first = branches.next().unwrap();
let second = branches.next().unwrap();
assert!(branches.next().is_none());
// First branch has value 2 and no children
let (value, mut branches) = first.read_node();
assert_eq!(2, value);
assert!(branches.next().is_none());
// Second branch has value 3 and one child with value 4
let (value, mut branches) = second.read_node();
assert_eq!(3, value);
assert_eq!(4, branches.next().unwrap().read_node().0);

无运行时依赖