-
Notifications
You must be signed in to change notification settings - Fork 0
/
generic_strconv.go
113 lines (92 loc) · 2 KB
/
generic_strconv.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
package faststrconv
type stringOrBytes interface {
~[]byte | ~string
}
// GetByte validates and converts input string or []byte to byte type.
func GetByte[I stringOrBytes](input I) (byte, error) {
if len(input)&^byteLengthMask != 0 || len(input) == 0 {
return 0, ErrNotByte
}
var i int
var output uint16
for {
if input[i]&^digitsMask > 9 {
return 0, ErrNotByte
}
output = uint16(input[i])&^digitsMask + output*10
i++
if i == len(input) {
if output&^maxByteMask != 0 {
return 0, ErrNotByte
}
break
}
}
return byte(output), nil
}
// GetCustomByte validates and converts input string or []byte to byte type.
func GetCustomByte[I stringOrBytes, V ~byte](input I) (V, error) {
if len(input)&^byteLengthMask != 0 || len(input) == 0 {
return 0, ErrNotByte
}
var i int
var output uint16
for {
if input[i]&^digitsMask > 9 {
return 0, ErrNotByte
}
output = uint16(input[i])&^digitsMask + output*10
i++
if i == len(input) {
if output&^maxByteMask != 0 {
return 0, ErrNotByte
}
break
}
}
return V(output), nil
}
// GetUint16 validates and converts input string or []byte to uint16 type.
func GetUint16[I stringOrBytes](input I) (uint16, error) {
if len(input) == 0 {
return 0, ErrNotUint16
}
var i int
var output uint32
for {
if input[i]&^digitsMask > 9 {
return 0, ErrNotUint16
}
output = output*10 + uint32(input[i])&^digitsMask
i++
if i == len(input) {
if output&^maxUint16Mask != 0 {
return 0, ErrNotUint16
}
break
}
}
return uint16(output), nil
}
// GetUint32 validates and converts input string or []byte to uint32 type.
func GetUint32[I stringOrBytes](input I) (uint32, error) {
if len(input) == 0 {
return 0, ErrNotUint32
}
var i int
var output uint64
for {
if input[i]&^digitsMask > 9 {
return 0, ErrNotUint32
}
output = uint64(input[i])&^digitsMask + output*10
i++
if i == len(input) {
if output&^maxUint32Mask != 0 {
return 0, ErrNotUint32
}
break
}
}
return uint32(output), nil
}