-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathbuffer.go
125 lines (104 loc) · 2.33 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
// Copyright 2020 Frederik Zipp. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package canvas
import (
"encoding/binary"
"image/color"
"math"
)
type buffer struct {
bytes []byte
error error
}
var byteOrder = binary.BigEndian
func (buf *buffer) addByte(b byte) {
buf.bytes = append(buf.bytes, b)
}
func (buf *buffer) addFloat64(f float64) {
buf.bytes = append(buf.bytes, 0, 0, 0, 0, 0, 0, 0, 0)
byteOrder.PutUint64(buf.bytes[len(buf.bytes)-8:], math.Float64bits(f))
}
func (buf *buffer) addUint32(i uint32) {
buf.bytes = append(buf.bytes, 0, 0, 0, 0)
byteOrder.PutUint32(buf.bytes[len(buf.bytes)-4:], i)
}
func (buf *buffer) addBool(b bool) {
if b {
buf.addByte(1)
} else {
buf.addByte(0)
}
}
func (buf *buffer) addBytes(p []byte) {
buf.bytes = append(buf.bytes, p...)
}
func (buf *buffer) addString(s string) {
buf.addUint32(uint32(len(s)))
buf.bytes = append(buf.bytes, []byte(s)...)
}
func (buf *buffer) addColor(c color.Color) {
clr := color.RGBAModel.Convert(c).(color.RGBA)
buf.addByte(clr.R)
buf.addByte(clr.G)
buf.addByte(clr.B)
buf.addByte(clr.A)
}
func (buf *buffer) readByte() byte {
if len(buf.bytes) < 1 {
buf.dataTooShort()
return 0
}
b := buf.bytes[0]
buf.bytes = buf.bytes[1:]
return b
}
func (buf *buffer) readUint32() uint32 {
if len(buf.bytes) < 4 {
buf.dataTooShort()
return 0
}
i := byteOrder.Uint32(buf.bytes)
buf.bytes = buf.bytes[4:]
return i
}
func (buf *buffer) readUint64() uint64 {
if len(buf.bytes) < 8 {
buf.dataTooShort()
return 0
}
i := byteOrder.Uint64(buf.bytes)
buf.bytes = buf.bytes[8:]
return i
}
func (buf *buffer) readFloat64() float64 {
return math.Float64frombits(buf.readUint64())
}
func (buf *buffer) readString() string {
length := int(buf.readUint32())
if len(buf.bytes) < length {
buf.dataTooShort()
return ""
}
s := string(buf.bytes[:length])
buf.bytes = buf.bytes[length:]
return s
}
func (buf *buffer) skip(nBytes int) {
if len(buf.bytes) < nBytes {
buf.dataTooShort()
return
}
buf.bytes = buf.bytes[nBytes:]
}
func (buf *buffer) reset() {
buf.bytes = make([]byte, 0, cap(buf.bytes))
}
func (buf *buffer) dataTooShort() {
buf.reset()
buf.error = errDataTooShort{}
}
type errDataTooShort struct{}
func (err errDataTooShort) Error() string {
return "data too short"
}