-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprimitive.go
More file actions
76 lines (69 loc) · 2.18 KB
/
Copy pathprimitive.go
File metadata and controls
76 lines (69 loc) · 2.18 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package ulogo
import (
"encoding/binary"
"fmt"
"math"
)
type primitiveType struct {
size int
}
var primitiveTypes = map[string]primitiveType{
"int8_t": {size: 1},
"uint8_t": {size: 1},
"int16_t": {size: 2},
"uint16_t": {size: 2},
"int32_t": {size: 4},
"uint32_t": {size: 4},
"int64_t": {size: 8},
"uint64_t": {size: 8},
"float": {size: 4},
"double": {size: 8},
"bool": {size: 1},
"char": {size: 1},
}
// FieldSize returns the byte width of a primitive ULog type.
func FieldSize(typeName string) (int, bool) {
info, ok := primitiveTypes[typeName]
return info.size, ok
}
func isPrimitive(typeName string) bool {
_, ok := primitiveTypes[typeName]
return ok
}
func decodePrimitive(typeName string, data []byte) (Value, error) {
size, ok := FieldSize(typeName)
if !ok {
return Value{}, fmt.Errorf("unknown ULog primitive type %q", typeName)
}
if len(data) < size {
return Value{}, fmt.Errorf("not enough bytes for %s: have %d need %d", typeName, len(data), size)
}
switch typeName {
case "int8_t":
return Value{Type: typeName, Any: int8(data[0])}, nil
case "uint8_t":
return Value{Type: typeName, Any: uint8(data[0])}, nil
case "int16_t":
return Value{Type: typeName, Any: int16(binary.LittleEndian.Uint16(data[:2]))}, nil
case "uint16_t":
return Value{Type: typeName, Any: binary.LittleEndian.Uint16(data[:2])}, nil
case "int32_t":
return Value{Type: typeName, Any: int32(binary.LittleEndian.Uint32(data[:4]))}, nil
case "uint32_t":
return Value{Type: typeName, Any: binary.LittleEndian.Uint32(data[:4])}, nil
case "int64_t":
return Value{Type: typeName, Any: int64(binary.LittleEndian.Uint64(data[:8]))}, nil
case "uint64_t":
return Value{Type: typeName, Any: binary.LittleEndian.Uint64(data[:8])}, nil
case "float":
return Value{Type: typeName, Any: math.Float32frombits(binary.LittleEndian.Uint32(data[:4]))}, nil
case "double":
return Value{Type: typeName, Any: math.Float64frombits(binary.LittleEndian.Uint64(data[:8]))}, nil
case "bool":
return Value{Type: typeName, Any: data[0] != 0}, nil
case "char":
return Value{Type: typeName, Any: data[0]}, nil
default:
return Value{}, fmt.Errorf("unknown ULog primitive type %q", typeName)
}
}