aboutsummaryrefslogtreecommitdiffstats
path: root/vendor/github.com/lunixbochs/struc/struc.go
blob: 3d85fe32140ed60178a459cf4617d1290b8f30a4 (plain)
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
package struc

import (
	"encoding/binary"
	"fmt"
	"io"
	"reflect"
)

type Options struct {
	ByteAlign int
	PtrSize   int
	Order     binary.ByteOrder
}

func (o *Options) Validate() error {
	if o.PtrSize == 0 {
		o.PtrSize = 32
	} else {
		switch o.PtrSize {
		case 8, 16, 32, 64:
		default:
			return fmt.Errorf("Invalid Options.PtrSize: %d. Must be in (8, 16, 32, 64)", o.PtrSize)
		}
	}
	return nil
}

var emptyOptions = &Options{}

func prep(data interface{}) (reflect.Value, Packer, error) {
	value := reflect.ValueOf(data)
	for value.Kind() == reflect.Ptr {
		next := value.Elem().Kind()
		if next == reflect.Struct || next == reflect.Ptr {
			value = value.Elem()
		} else {
			break
		}
	}
	switch value.Kind() {
	case reflect.Struct:
		fields, err := parseFields(value)
		return value, fields, err
	default:
		if !value.IsValid() {
			return reflect.Value{}, nil, fmt.Errorf("Invalid reflect.Value for %+v", data)
		}
		if c, ok := data.(Custom); ok {
			return value, customFallback{c}, nil
		}
		return value, binaryFallback(value), nil
	}
}

func Pack(w io.Writer, data interface{}) error {
	return PackWithOptions(w, data, nil)
}

func PackWithOptions(w io.Writer, data interface{}, options *Options) error {
	if options == nil {
		options = emptyOptions
	}
	if err := options.Validate(); err != nil {
		return err
	}
	val, packer, err := prep(data)
	if err != nil {
		return err
	}
	if val.Type().Kind() == reflect.String {
		val = val.Convert(reflect.TypeOf([]byte{}))
	}
	size := packer.Sizeof(val, options)
	buf := make([]byte, size)
	if _, err := packer.Pack(buf, val, options); err != nil {
		return err
	}
	_, err = w.Write(buf)
	return err
}

func Unpack(r io.Reader, data interface{}) error {
	return UnpackWithOptions(r, data, nil)
}

func UnpackWithOptions(r io.Reader, data interface{}, options *Options) error {
	if options == nil {
		options = emptyOptions
	}
	if err := options.Validate(); err != nil {
		return err
	}
	val, packer, err := prep(data)
	if err != nil {
		return err
	}
	return packer.Unpack(r, val, options)
}

func Sizeof(data interface{}) (int, error) {
	return SizeofWithOptions(data, nil)
}

func SizeofWithOptions(data interface{}, options *Options) (int, error) {
	if options == nil {
		options = emptyOptions
	}
	if err := options.Validate(); err != nil {
		return 0, err
	}
	val, packer, err := prep(data)
	if err != nil {
		return 0, err
	}
	return packer.Sizeof(val, options), nil
}