summaryrefslogtreecommitdiff
path: root/lib/containers/sortedmap.go
blob: d6d2f9e3f12cd39d060aa767f796b7ffdc4daad3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// Copyright (C) 2022  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package containers

import (
	"errors"
)

type OrderedKV[K Ordered[K], V any] struct {
	K K
	V V
}

type SortedMap[K Ordered[K], V any] struct {
	inner RBTree[K, OrderedKV[K, V]]
}

func (m *SortedMap[K, V]) init() {
	if m.inner.KeyFn == nil {
		m.inner.KeyFn = m.keyFn
	}
}

func (m *SortedMap[K, V]) keyFn(kv OrderedKV[K, V]) K {
	return kv.K
}

func (m *SortedMap[K, V]) Delete(key K) {
	m.init()
	m.inner.Delete(key)
}

func (m *SortedMap[K, V]) Load(key K) (value V, ok bool) {
	m.init()
	node := m.inner.Lookup(key)
	if node == nil {
		var zero V
		return zero, false
	}
	return node.Value.V, true
}

var errStop = errors.New("stop")

func (m *SortedMap[K, V]) Range(f func(key K, value V) bool) {
	m.init()
	_ = m.inner.Walk(func(node *RBNode[OrderedKV[K, V]]) error {
		if f(node.Value.K, node.Value.V) {
			return nil
		} else {
			return errStop
		}
	})
}

func (m *SortedMap[K, V]) Subrange(rangeFn func(K, V) int, handleFn func(K, V) bool) {
	m.init()
	kvs := m.inner.SearchRange(func(kv OrderedKV[K, V]) int {
		return rangeFn(kv.K, kv.V)
	})
	for _, kv := range kvs {
		if !handleFn(kv.K, kv.V) {
			break
		}
	}
}

func (m *SortedMap[K, V]) Store(key K, value V) {
	m.init()
	m.inner.Insert(OrderedKV[K, V]{
		K: key,
		V: value,
	})
}

func (m *SortedMap[K, V]) Search(fn func(K, V) int) (K, V, bool) {
	node := m.inner.Search(func(kv OrderedKV[K, V]) int {
		return fn(kv.K, kv.V)
	})
	if node == nil {
		var zeroK K
		var zeroV V
		return zeroK, zeroV, false
	}
	return node.Value.K, node.Value.V, true
}

func (m *SortedMap[K, V]) SearchAll(fn func(K, V) int) []OrderedKV[K, V] {
	return m.inner.SearchRange(func(kv OrderedKV[K, V]) int {
		return fn(kv.K, kv.V)
	})
}