/
buffer.go
67 lines (59 loc) · 1.51 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
package gophoenixsocketclient
import (
"sync"
)
// Buffer Offset writable memory buffer.
// Reference by: https://github.com/aws/aws-sdk-go/blob/v1.44.33/aws/types.go#L163-L172
type Buffer struct {
buf []byte
l int64
mut sync.Mutex
Grow float64
}
// NewBuffer make offset writable memory buffer.
func NewBuffer(l int64) *Buffer {
return &Buffer{buf: make([]byte, l), l: l}
}
// NewBufferFromValues make offset writable memory buffer with defined buf.
func NewBufferFromValues(buf []byte) *Buffer {
return &Buffer{buf: buf, l: int64(cap(buf))}
}
// WriteAt write memory buffer with offset position
func (buf *Buffer) WriteAt(payload []byte, offset int64) (n int, err error) {
n = len(payload)
afterLength := offset + int64(n)
buf.mut.Lock()
defer buf.mut.Unlock()
if int64(len(buf.buf)) < afterLength {
if int64(cap(buf.buf)) < afterLength {
if buf.Grow < 1 {
buf.Grow = 1
}
newBuffer := make([]byte, afterLength, int64(buf.Grow*float64(afterLength)))
copy(newBuffer, buf.buf)
buf.buf = newBuffer
}
buf.buf = buf.buf[:afterLength]
}
copy(buf.buf[offset:], payload)
return n, err
}
// Bytes returns all bytes in the memory buffer.
func (buf *Buffer) Bytes() []byte {
buf.mut.Lock()
defer buf.mut.Unlock()
return buf.buf
}
// Length returns the size of the memory buffer.
func (buf *Buffer) Length() int64 {
buf.mut.Lock()
defer buf.mut.Unlock()
return buf.l
}
// Reset clears the memory buffer.
func (buf *Buffer) Reset() {
buf.mut.Lock()
buf.buf = nil
buf.l = 0
buf.mut.Unlock()
}