-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuffer.go
73 lines (61 loc) · 1.28 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
package netfilter
import (
"bytes"
"container/list"
)
type Buffer struct {
packets *list.List
}
type packet struct {
Data []byte
}
func NewBuffer() (*Buffer, error) {
ds := &Buffer{
packets: list.New(),
}
return ds, nil
}
func (ds *Buffer) Write(buf []byte) error {
dst := make([]byte, len(buf))
copy(dst, buf)
return ds.WriteNoCopy(buf)
}
func (ds *Buffer) WriteNoCopy(buf []byte) error {
packet := &packet{Data: buf}
ds.packets.PushBack(packet)
return nil
}
func (ds *Buffer) Next(numBytes int) ([]byte, error) {
return ds.getData(numBytes, true)
}
func (ds *Buffer) Peek(numBytes int) ([]byte, error) {
return ds.getData(numBytes, false)
}
func (ds *Buffer) PutBack(buf []byte) error {
ds.packets.PushFront(&packet{Data: buf})
return nil
}
func (ds *Buffer) getData(numBytes int, destructive bool) ([]byte, error) {
buf := bytes.NewBuffer(make([]byte, 512))
for e := ds.packets.Front(); e != nil; e = e.Next() {
packet := e.Value.(*packet)
len := len(packet.Data)
if len > numBytes {
buf.Write(packet.Data[:numBytes])
if destructive {
packet.Data = packet.Data[numBytes:]
}
break
} else {
buf.Write(packet.Data)
if destructive {
ds.packets.Remove(e)
}
numBytes -= len
if numBytes == 0 {
break
}
}
}
return buf.Bytes(), nil
}