group.go 1.85 KB
Newer Older
Jeromy's avatar
Jeromy committed
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
package peerstream

import (
	"errors"
	"sync"
	"unsafe"
)

// ErrGroupNotFound signals no such group exists
var ErrGroupNotFound = errors.New("group not found")

// Group is an object used to associate a group of
// Streams, Connections, and Listeners. It can be anything,
// it is meant to work like a KeyType in maps
type Group interface{}

// Groupable is an interface for a set of objects that can
// be assigned groups: Streams, Connections, and Listeners.
// Objects inherit groups (e.g. a Stream inherits the groups
// of its parent Connection, and in turn that of its Listener).
type Groupable interface {
	// Groups returns the groups this object belongs to
	Groups() []Group

	// InGroup returns whether this object belongs to a Group
	InGroup(g Group) bool

	// AddGroup adds this object to a group
	AddGroup(g Group)
}

// groupSet is a struct designed to be embedded and
// give things group memebership
type groupSet struct {
	m map[Group]struct{}
	sync.RWMutex
}

func (gs *groupSet) Add(g Group) {
	gs.Lock()
	defer gs.Unlock()
	gs.m[g] = struct{}{}
}

func (gs *groupSet) Remove(g Group) {
	gs.Lock()
	defer gs.Unlock()
	delete(gs.m, g)
}

func (gs *groupSet) Has(g Group) bool {
	gs.RLock()
	defer gs.RUnlock()
	_, ok := gs.m[g]
	return ok
}

func (gs *groupSet) Groups() []Group {
	gs.RLock()
	defer gs.RUnlock()

	out := make([]Group, 0, len(gs.m))
	for k := range gs.m {
		out = append(out, k)
	}
	return out
}

// AddSet adds all elements in another set.
func (gs *groupSet) AddSet(gs2 *groupSet) {
	// acquire locks in order
	p1 := uintptr(unsafe.Pointer(gs))
	p2 := uintptr(unsafe.Pointer(gs2))
	switch {
	case p1 < p2:
		gs.Lock()
		gs2.RLock()
		defer gs.Unlock()
		defer gs2.RUnlock()
	case p1 > p2:
		gs2.Lock()
		gs.Lock()
		defer gs2.Unlock()
		defer gs.Unlock()
	default:
		return // they're the same!
	}

	for g := range gs2.m {
		gs.m[g] = struct{}{}
	}
}