-
Notifications
You must be signed in to change notification settings - Fork 1
/
buffer.go
104 lines (93 loc) · 2.26 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
103
104
package ioengine
import (
"errors"
"io"
"unsafe"
)
// MemAlignWithBase like linux posix_memalign.
// block start address must be a multiple of AlignSize.
// block size also must be a multiple of AlignSize.
func MemAlignWithBase(blockSize, alignSize uint) ([]byte, error) {
// make sure blockSize is a multiple of AlignSize.
if alignSize != 0 && blockSize&(alignSize-1) != 0 {
return nil, errors.New("invalid argument")
}
block := make([]byte, blockSize+alignSize)
remainder := alignment(block, alignSize)
var offset uint
if remainder != 0 {
offset = alignSize - remainder
}
return block[offset : offset+blockSize], nil
}
// MemAlign mem align
func MemAlign(blockSize uint) ([]byte, error) {
return MemAlignWithBase(blockSize, AlignSize)
}
// alignment returns alignment of the block address in memory with reference to alignSize.
func alignment(block []byte, alignSize uint) uint {
// if block is nil or length is 0, it will return 0.
if len(block) < 1 {
return 0
}
// make sure a bit operation mod divisor must be a multiple of 2.
if alignSize == 0 || alignSize == 1 || alignSize&1 != 0 {
return 0
}
return uint(uintptr(unsafe.Pointer(&block[0])) & uintptr(alignSize-1))
}
// Buffers contains zero or more runs of bytes to write.
// this is applied to readv, writev, preadv, pwritev.
type Buffers [][]byte
// NewBuffers init buffer slice by default cap 128
func NewBuffers() *Buffers {
buffers := make(Buffers, 0, 128)
return &buffers
}
func (v *Buffers) Write(b []byte) *Buffers {
*v = append(*v, b)
return v
}
func (v *Buffers) Read(b []byte) (n int, err error) {
for len(b) > 0 && len(*v) > 0 {
n0 := copy(b, (*v)[0])
v.consume(int64(n0))
b = b[n0:]
n += n0
}
if len(*v) == 0 {
err = io.EOF
}
return
}
// WriteTo direct write to writer
func (v *Buffers) WriteTo(w io.Writer) (n int64, err error) {
for _, b := range *v {
nb, err := w.Write(b)
n += int64(nb)
if err != nil {
v.consume(n)
return n, err
}
}
v.consume(n)
return n, nil
}
// Length return buffers byte total length
func (v *Buffers) Length() (n int) {
for _, b := range *v {
n += len(b)
}
return n
}
func (v *Buffers) consume(n int64) {
for len(*v) > 0 {
ln0 := int64(len((*v)[0]))
if ln0 > n {
(*v)[0] = (*v)[0][n:]
return
}
n -= ln0
*v = (*v)[1:]
}
}