This repository has been archived by the owner on Sep 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
bridges.go
95 lines (75 loc) · 1.78 KB
/
bridges.go
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
95
package domain
import (
"errors"
"net"
"sync"
"code.cloudfoundry.org/lager"
)
var BridgeProvider = NewBridge
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 . Bridges
type Bridges interface {
Create(clientConn, backendConn net.Conn) Bridge
Remove(bridge Bridge) error
RemoveAndCloseAll()
Size() uint
Contains(bridge Bridge) bool
}
type concurrentBridges struct {
mutex sync.RWMutex
bridges []Bridge
logger lager.Logger
}
func NewBridges(logger lager.Logger) Bridges {
return &concurrentBridges{
logger: logger,
}
}
func (b *concurrentBridges) Create(clientConn, backendConn net.Conn) Bridge {
b.mutex.Lock()
defer b.mutex.Unlock()
bridge := BridgeProvider(clientConn, backendConn, b.logger)
b.bridges = append(b.bridges, bridge)
return bridge
}
func (b *concurrentBridges) Remove(bridge Bridge) error {
b.mutex.Lock()
defer b.mutex.Unlock()
if !b.unsafeContains(bridge) {
return errors.New("Bridge not found")
}
index := b.unsafeIndexOf(bridge)
copy(b.bridges[index:], b.bridges[index+1:])
b.bridges = b.bridges[:len(b.bridges)-1]
return nil
}
func (b *concurrentBridges) RemoveAndCloseAll() {
b.mutex.Lock()
defer b.mutex.Unlock()
for _, bridge := range b.bridges {
bridge.Close()
}
b.bridges = []Bridge{}
}
func (b *concurrentBridges) Size() uint {
b.mutex.RLock()
defer b.mutex.RUnlock()
return uint(len(b.bridges))
}
func (b *concurrentBridges) Contains(bridge Bridge) bool {
b.mutex.RLock()
defer b.mutex.RUnlock()
return b.unsafeContains(bridge)
}
func (b *concurrentBridges) unsafeContains(bridge Bridge) bool {
return b.unsafeIndexOf(bridge) != -1
}
func (b *concurrentBridges) unsafeIndexOf(bridge Bridge) int {
index := -1
for i, aBridge := range b.bridges {
if aBridge == bridge {
index = i
break
}
}
return index
}