-
Notifications
You must be signed in to change notification settings - Fork 95
/
portmanager.go
58 lines (51 loc) · 937 Bytes
/
portmanager.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
package gb28181
import (
"errors"
)
var ErrNoAvailablePorts = errors.New("no available ports")
type PortManager struct {
recycle chan uint16
start uint16
max uint16
pos uint16
Valid bool
}
func (pm *PortManager) Init(start, end uint16) {
pm.start = start
pm.pos = start - 1
pm.max = end
if pm.pos > 0 && pm.max > pm.pos {
pm.Valid = true
pm.recycle = make(chan uint16, pm.Range())
}
}
func (pm *PortManager) Range() uint16 {
return pm.max - pm.pos
}
func (pm *PortManager) Recycle(p uint16) (err error) {
select {
case pm.recycle <- p:
return nil
default:
return ErrNoAvailablePorts
}
}
func (pm *PortManager) GetPort() (p uint16, err error) {
select {
case p = <-pm.recycle:
return
default:
if pm.Range() > 0 {
pm.pos++
p = pm.pos
return
} else {
if conf.Port.Fdm == false {
return 0, ErrNoAvailablePorts
}
pm.pos = pm.start - 1
p = pm.pos
return
}
}
}