aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/sync/map.go
blob: f27450ce5ed879f7eac054d09d60133a89cc56ad (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
package sync

// This file implements just enough of sync.Map to get packages to compile. It
// is no more efficient than a map with a lock.

type Map struct {
	lock Mutex
	m    map[interface{}]interface{}
}

func (m *Map) Delete(key interface{}) {
	m.lock.Lock()
	defer m.lock.Unlock()
	delete(m.m, key)
}

func (m *Map) Load(key interface{}) (value interface{}, ok bool) {
	m.lock.Lock()
	defer m.lock.Unlock()
	value, ok = m.m[key]
	return
}

func (m *Map) LoadOrStore(key, value interface{}) (actual interface{}, loaded bool) {
	m.lock.Lock()
	defer m.lock.Unlock()
	if m.m == nil {
		m.m = make(map[interface{}]interface{})
	}
	if existing, ok := m.m[key]; ok {
		return existing, true
	}
	m.m[key] = value
	return value, false
}

func (m *Map) LoadAndDelete(key interface{}) (value interface{}, loaded bool) {
	m.lock.Lock()
	defer m.lock.Unlock()
	value, ok := m.m[key]
	if !ok {
		return nil, false
	}
	delete(m.m, key)
	return value, true
}

func (m *Map) Store(key, value interface{}) {
	m.lock.Lock()
	defer m.lock.Unlock()
	if m.m == nil {
		m.m = make(map[interface{}]interface{})
	}
	m.m[key] = value
}

func (m *Map) Range(f func(key, value interface{}) bool) {
	m.lock.Lock()
	defer m.lock.Unlock()

	if m.m == nil {
		return
	}

	for k, v := range m.m {
		if !f(k, v) {
			break
		}
	}
}