go-immutable-radix
提供 iradix 包,它实现了一个不可变的 radix 树。该包只提供了一个单一的 Tree 实现,针对稀疏节点进行了优化。
作为一个 radix 树,它提供了以下功能。
- O(k)操作. 在许多情况下,这可以比哈希表更快,因为哈希函数是一个O(k)操作,而哈希表的缓存定位性非常差。
- 最小值/最大值查询
- 有序迭代
树支持使用事务以比一次执行每个操作更有效的方式批量更新(插入、删除)。
对于一个可变异的变体,请参见 go-radix。
文档
完整的文档可以在 Godoc 上找到。
例子
下面是一个简单的使用实例
// Create a tree r := iradix.New() r, _, _ = r.Insert([]byte("foo"), 1) r, _, _ = r.Insert([]byte("bar"), 2) r, _, _ = r.Insert([]byte("foobar"), 2) // Find the longest prefix match m, _, _ := r.Root().LongestPrefix([]byte("foozip")) if string(m) != "foo" { panic("should be foo") }
下面是一个对按键进行范围扫描的例子。
// Create a tree r := iradix.New() r, _, _ = r.Insert([]byte("001"), 1) r, _, _ = r.Insert([]byte("002"), 2) r, _, _ = r.Insert([]byte("005"), 5) r, _, _ = r.Insert([]byte("010"), 10) r, _, _ = r.Insert([]byte("100"), 10) // Range scan over the keys that sort lexicographically between [003, 050) it := r.Root().Iterator() it.SeekLowerBound([]byte("003")) for key, _, ok := it.Next(); ok; key, _, ok = it.Next() { if key >= "050" { break } fmt.Println(key) } // Output: // 005 // 010