-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_array_test.go
More file actions
62 lines (52 loc) · 1.22 KB
/
example_array_test.go
File metadata and controls
62 lines (52 loc) · 1.22 KB
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
package lexy_test
import (
"bytes"
"fmt"
"math"
"github.com/phiryll/lexy"
)
type Quaternion [4]float64
type quaternionCodec struct{}
var quatCodec lexy.Codec[Quaternion] = quaternionCodec{}
func (quaternionCodec) Append(buf []byte, value Quaternion) []byte {
for i := range value {
buf = lexy.Float64().Append(buf, value[i])
}
return buf
}
func (quaternionCodec) Put(buf []byte, value Quaternion) []byte {
for i := range value {
buf = lexy.Float64().Put(buf, value[i])
}
return buf
}
func (quaternionCodec) Get(buf []byte) (Quaternion, []byte) {
var value Quaternion
for i := range value {
value[i], buf = lexy.Float64().Get(buf)
}
return value, buf
}
func (quaternionCodec) RequiresTerminator() bool {
return false
}
// ExampleArray shows how to define a Codec for an array type.
func Example_array() {
quats := []Quaternion{
{0.0, 3.4, 2.1, -1.5},
{-9.3e+10, 7.6, math.Inf(1), 42.0},
}
for _, quat := range quats {
appendBuf := quatCodec.Append(nil, quat)
putBuf := make([]byte, 4*8)
quatCodec.Put(putBuf, quat)
fmt.Println(bytes.Equal(appendBuf, putBuf))
decoded, _ := quatCodec.Get(appendBuf)
fmt.Println(decoded)
}
// Output:
// true
// [0 3.4 2.1 -1.5]
// true
// [-9.3e+10 7.6 +Inf 42]
}