/
static.go
96 lines (83 loc) · 1.98 KB
/
static.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
// Copyright (c) 2018 Timo Savola. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package buffer
import (
"encoding/binary"
"io"
)
// Static is a fixed-capacity buffer, for wrapping a memory-mapped region. The
// default value is a zero-capacity buffer.
type Static struct {
buf []byte
}
// MakeStatic buffer.
//
// This function can be used in field initializer expressions. The initialized
// field must not be copied.
func MakeStatic(b []byte) Static {
return Static{b}
}
// NewStatic buffer.
func NewStatic(b []byte) *Static {
s := MakeStatic(b)
return &s
}
// Capacity of the static buffer.
func (s *Static) Cap() int {
return cap(s.buf)
}
// Len doesn't panic.
func (s *Static) Len() int {
return len(s.buf)
}
// Bytes doesn't panic.
func (s *Static) Bytes() []byte {
return s.buf
}
// Write doesn't panic.
func (s *Static) Write(b []byte) (n int, err error) {
offset := len(s.buf)
size := offset + len(b)
if size <= cap(s.buf) {
s.buf = s.buf[:size]
} else {
s.buf = s.buf[:cap(s.buf)]
err = io.EOF
}
n = copy(s.buf[offset:], b)
return
}
// PutByte panicks with ErrSizeLimit if the buffer is already full.
func (s *Static) PutByte(value byte) {
offset := len(s.buf)
if offset >= cap(s.buf) {
panic(ErrSizeLimit)
}
s.buf = s.buf[:offset+1]
s.buf[offset] = value
}
// Extend panicks with ErrSizeLimit if 4 bytes cannot be appended to the
// buffer.
func (s *Static) PutUint32(i uint32) {
binary.LittleEndian.PutUint32(s.Extend(4), i)
}
// Extend panicks with ErrSizeLimit if n bytes cannot be appended to the
// buffer.
func (s *Static) Extend(n int) []byte {
offset := len(s.buf)
size := offset + n
if size > cap(s.buf) {
panic(ErrSizeLimit)
}
s.buf = s.buf[:size]
return s.buf[offset:]
}
// ResizeBytes panicks with ErrSizeLimit if n is larger than buffer capacity.
func (s *Static) ResizeBytes(n int) []byte {
if n > cap(s.buf) {
panic(ErrSizeLimit)
}
s.buf = s.buf[:n]
return s.buf
}