summaryrefslogtreecommitdiff
path: root/lib/containers/maputil.go
blob: 4d49d2ac782c142a1725bcac03bc3a145f714d24 (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
// Copyright (C) 2023  Luke Shumaker <lukeshu@lukeshu.com>
//
// SPDX-License-Identifier: GPL-2.0-or-later

package containers

type Map[K comparable, V any] interface {
	Store(K, V)
	Load(K) (V, bool)
	Has(K) bool
	Delete(K)
	Len() int
}

type RangeMap[K comparable, V any] interface {
	Map[K, V]
	Range(func(K, V) bool)
}

type SubrangeMap[K comparable, V any] interface {
	RangeMap[K, V]
	Subrange(rangeFn func(K, V) int, handleFn func(K, V) bool)
}

func LoadOrElse[K comparable, V any](m Map[K, V], k K, vFn func(K) V) V {
	if v, ok := m.Load(k); ok {
		return v
	}
	v := vFn(k)
	m.Store(k, v)
	return v
}