This repository was archived by the owner on Feb 3, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtype.go
120 lines (106 loc) · 2.15 KB
/
type.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
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
118
119
120
package gokdl
import (
"fmt"
"strconv"
)
type TypeAnnotation string
func (t TypeAnnotation) String() string {
return string(t)
}
const (
noTypeAnnot = ""
I8 TypeAnnotation = "i8"
I16 TypeAnnotation = "i16"
I32 TypeAnnotation = "i32"
I64 TypeAnnotation = "i64"
U8 TypeAnnotation = "u8"
U16 TypeAnnotation = "u16"
U32 TypeAnnotation = "u32"
U64 TypeAnnotation = "u64"
F32 TypeAnnotation = "f32"
F64 TypeAnnotation = "f64"
)
var (
numberTypeAnnotation = map[string]TypeAnnotation{
I8.String(): I8,
I16.String(): I16,
I32.String(): I32,
I64.String(): I64,
U8.String(): U8,
U16.String(): U16,
U32.String(): U32,
U64.String(): U64,
F32.String(): F32,
F64.String(): F64,
}
)
func init() {
nums := []TypeAnnotation{
I8,
I16,
I32,
I64,
U8,
U16,
U32,
U64,
F32,
F64,
}
for _, n := range nums {
numberTypeAnnotation[n.String()] = n
}
}
func parseStringValue(value, typeAnnot string) (string, error) {
if _, isNum := numberTypeAnnotation[typeAnnot]; isNum {
return "", fmt.Errorf("invalid type annotation for type string: %s", typeAnnot)
}
return value, nil
}
func parseIntValue(value, typeAnnot string) (any, error) {
var bitsize int
var unsigned bool
switch TypeAnnotation(typeAnnot) {
case noTypeAnnot:
bitsize = 64
case I8:
bitsize = 8
case I16:
bitsize = 16
case I32:
bitsize = 32
case I64:
bitsize = 64
case U8:
bitsize = 8
unsigned = true
case U16:
bitsize = 16
unsigned = true
case U32:
bitsize = 32
unsigned = true
case U64:
bitsize = 64
unsigned = true
default:
return value, fmt.Errorf("invalid type annotation for integer: %s", typeAnnot)
}
if unsigned {
return strconv.ParseUint(value, 10, bitsize)
} else {
return strconv.ParseInt(value, 10, bitsize)
}
}
func parseFloatValue(value, typeAnnot string) (any, error) {
var bitsize int
switch TypeAnnotation(typeAnnot) {
case F32:
bitsize = 32
case noTypeAnnot, F64:
bitsize = 64
default:
return value, fmt.Errorf("invalid type annotation for integer: %s", typeAnnot)
}
return strconv.ParseFloat(value, bitsize)
}