-
Notifications
You must be signed in to change notification settings - Fork 0
/
cast.go
53 lines (45 loc) · 1.48 KB
/
cast.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
package bin
import (
"errors"
"fmt"
"reflect"
"unsafe"
)
var (
errPtrPtrStructRequired = errors.New("pointer to pointer of go structure required")
)
type emptyIfc struct {
typ, ptr unsafe.Pointer
}
// UnsafeCastStruct casts a byte slice its contents into an arbitrary go-structure.
// The structure passed must be a pointer to a pointer of a struct to be casted too.
//
// If the input buffers length is 0, `to` will be set to nil.
//
// The operation is unsafe, as it does not validate the input value to be a
// pointer of a pointer, plus no length check is executed.
func UnsafeCastStruct(to interface{}, b []byte) {
ifc := (*emptyIfc)(unsafe.Pointer(&to))
if len(b) != 0 {
*(*uintptr)(ifc.ptr) = uintptr(unsafe.Pointer(&b[0]))
} else {
*(*uintptr)(ifc.ptr) = 0
}
}
// CastStruct casts a byte slice its contents into an arbitrary go-structure.
// The structure passed must be a pointer to a pointer of a structed to be casted too.
// An error is returned if the input type is invalid or the buffer is not big
// enough to hold the structure.
// If the input buffers length is 0, `to` will be set to nil.
func CastStruct(to interface{}, b []byte) error {
v := reflect.ValueOf(to)
if v.Kind() != reflect.Ptr || v.Elem().Kind() != reflect.Ptr {
return errPtrPtrStructRequired
}
if bl, tl := len(b), int(v.Type().Size()); 0 < bl && bl < tl {
return fmt.Errorf("buffer of %v byte(s) can not be casted into structure requiring %v byte(s)",
bl, tl)
}
UnsafeCastStruct(to, b)
return nil
}