diff --git a/tree_map.go b/tree_map.go index 4eb56eb..c6afd43 100644 --- a/tree_map.go +++ b/tree_map.go @@ -1,3 +1,7 @@ +/* +This is an implemenation of a tree map using a red-black tree. This can be used when +ranging through the key value pairs needs to be deterministic. +*/ package tree import ( @@ -8,11 +12,14 @@ import ( "golang.org/x/exp/constraints" ) +// Map is the tree map structure type Map[K constraints.Ordered, V any] struct { rbt *rb.Tree[K, V] size int } +// NewMap is used to create a new tree map. The keys must be +// an Ordered type and the value can be anything. func NewMap[K constraints.Ordered, V any]() *Map[K, V] { return &Map[K, V]{ rbt: &rb.Tree[K, V]{}, @@ -20,19 +27,27 @@ func NewMap[K constraints.Ordered, V any]() *Map[K, V] { } } +// Store will store the value with the key. If the +// key already has an value, the value passed will replace it. func (m *Map[K, V]) Store(k K, v V) { m.rbt.Insert(rb.Pair[K, V]{Key: k, Value: v}) m.size++ } +// Load will return the key's value. func (m *Map[K, V]) Load(k K) (V, bool) { return m.rbt.Search(k) } +// Len is the number of keys in the map. func (m *Map[_, _]) Len() int { return m.size } +// Range will pass the key value pair to the handler in the key's decending +// order. +// +// If the handler would like to break out of the range, return io.EOF. func (m *Map[K, V]) Range(handler func(k K, v V) error) error { pairs := m.rbt.Inorder()