Documentation ¶
Overview ¶
Package rope provides an implementation of a rope data structure. A rope provides the same interface as an array, but supports efficient insertion and deletion from the middle of the array. It is implemented as an augmented binary search tree. The rope supports the following operations, where 'n' is the number of elements in the rope:
* Remove: O(lg n).
* Insert: O(lg n).
* Slice: O(lg n + m), where m is the size of the slice.
* At: O(lg n).
A rope will be slower than an array for lookup, but faster for modification, and lookup is still logarithmic, which can be acceptable for many applications, whereas modification of an array is linear time in the worst case, which is often unacceptable.
Example ¶
package main import ( "fmt" "github.com/zendesk/generic/rope" ) func main() { r := rope.New[byte]([]byte("hello world")) fmt.Println(string(r.At(0))) r.Remove(6, r.Len()) r.Insert(6, []byte("rope")) fmt.Println(string(r.Value())) }
Output: h hello rope
Index ¶
- Variables
- type Node
- func (n *Node[V]) At(pos int) V
- func (n *Node[V]) Each(fn func(n *Node[V]))
- func (n *Node[V]) Insert(pos int, value []V)
- func (n *Node[V]) Len() int
- func (n *Node[V]) Rebalance()
- func (n *Node[V]) Rebuild()
- func (n *Node[V]) Remove(start, end int)
- func (n *Node[V]) Slice(start, end int) []V
- func (n *Node[V]) SplitAt(i int) (*Node[V], *Node[V])
- func (n *Node[V]) Value() []V
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // SplitLength is the threshold above which slices will be split into // separate nodes. SplitLength = 4096 * 4 // JoinLength is the threshold below which nodes will be merged into // slices. JoinLength = SplitLength / 2 // RebalanceRatio is the threshold used to trigger a rebuild during a // rebalance operation. RebalanceRatio = 1.2 )
Functions ¶
This section is empty.
Types ¶
type Node ¶
type Node[V any] struct { // contains filtered or unexported fields }
A Node in the rope structure. If the kind is tLeaf, only the value and length are valid, and if the kind is tNode, only length, left, right are valid.
func New ¶
New returns a new rope node from the given byte slice. The underlying data is not copied so the user should ensure that it is okay to insert and delete from the input slice.
func (*Node[V]) Rebalance ¶
func (n *Node[V]) Rebalance()
Rebalance finds unbalanced nodes and rebuilds them.
func (*Node[V]) Rebuild ¶
func (n *Node[V]) Rebuild()
Rebuild rebuilds the entire rope structure, resulting in a balanced tree.
func (*Node[V]) Slice ¶
Slice returns the range of the rope from [start:end). The returned slice is not copied.