-
Notifications
You must be signed in to change notification settings - Fork 22
/
example01_test.go
66 lines (53 loc) · 1.13 KB
/
example01_test.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
package binstruct_test
import (
"bytes"
"encoding/binary"
"fmt"
"github.com/davecgh/go-spew/spew"
"github.com/ghostiam/binstruct"
)
type dataWithNullTerminatedString struct {
ID int32
Type string `bin:"NullTerminatedString"`
OtherID int32
}
func (*dataWithNullTerminatedString) NullTerminatedString(r binstruct.Reader) (string, error) {
var b []byte
for {
readByte, err := r.ReadByte()
if binstruct.IsEOF(err) {
break
}
if err != nil {
return "", err
}
if readByte == 0x00 {
break
}
b = append(b, readByte)
}
return string(b), nil
}
func Example_decoderDataWithNullTerminatedString() {
b := []byte{
// ID
0x00, 0x00, 0x00, 0x05,
// Type as null-terminated string
't', 'e', 's', 't', 0x00,
// OtherID
0xff, 0xff, 0xff, 0xf0,
}
var actual dataWithNullTerminatedString
decoder := binstruct.NewDecoder(bytes.NewReader(b), binary.BigEndian)
err := decoder.Decode(&actual)
if err != nil {
panic(err)
}
fmt.Print(spew.Sdump(actual))
// Output:
// (binstruct_test.dataWithNullTerminatedString) {
// ID: (int32) 5,
// Type: (string) (len=4) "test",
// OtherID: (int32) -16
// }
}