forked from v2fly/v2ray-core
-
Notifications
You must be signed in to change notification settings - Fork 1
/
buffer.go
102 lines (85 loc) · 1.59 KB
/
buffer.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
96
97
98
99
100
101
102
package kcp
import (
"sync"
"v2ray.com/core/common/alloc"
)
const (
NumDistro = 5
DistroSize = 1600
)
type Buffer struct {
sync.Mutex
buffer *alloc.Buffer
next int
released int
hold bool
distro [NumDistro]*alloc.Buffer
}
func NewBuffer() *Buffer {
b := &Buffer{
next: 0,
released: 0,
hold: true,
buffer: alloc.NewBuffer(),
}
for idx := range b.distro {
content := b.buffer.Value[idx*DistroSize : (idx+1)*DistroSize]
b.distro[idx] = alloc.CreateBuffer(content, b)
}
return b
}
func (this *Buffer) IsEmpty() bool {
this.Lock()
defer this.Unlock()
return this.next == NumDistro
}
func (this *Buffer) Allocate() *alloc.Buffer {
this.Lock()
defer this.Unlock()
if this.next == NumDistro {
return nil
}
b := this.distro[this.next]
this.next++
return b
}
func (this *Buffer) Free(b *alloc.Buffer) {
this.Lock()
defer this.Unlock()
this.released++
if !this.hold && this.released == this.next {
this.ReleaseBuffer()
}
}
func (this *Buffer) Release() {
this.Lock()
defer this.Unlock()
if this.next == this.released {
this.ReleaseBuffer()
}
this.hold = false
}
func (this *Buffer) ReleaseBuffer() {
this.buffer.Release()
this.buffer = nil
for idx := range this.distro {
this.distro[idx] = nil
}
}
var (
globalBuffer *Buffer
globalBufferAccess sync.Mutex
)
func AllocateBuffer() *alloc.Buffer {
globalBufferAccess.Lock()
defer globalBufferAccess.Unlock()
if globalBuffer == nil {
globalBuffer = NewBuffer()
}
b := globalBuffer.Allocate()
if globalBuffer.IsEmpty() {
globalBuffer.Release()
globalBuffer = nil
}
return b
}