-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathparser.go
70 lines (57 loc) · 1.15 KB
/
parser.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
package fpdecimal
const sep = '.'
type errorString struct{ v string }
func (e *errorString) Error() string { return e.v }
var (
errEmptyString = &errorString{"empty string"}
errMissingDigitsAfterSign = &errorString{"missing digits after sign"}
errBadDigit = &errorString{"bad digit"}
errMultipleDots = &errorString{"multiple dots"}
)
// ParseFixedPointDecimal parses fixed-point decimal of p fractions into int64.
func ParseFixedPointDecimal(s []byte, p uint8) (int64, error) {
if len(s) == 0 {
return 0, errEmptyString
}
s0 := s
if s[0] == '-' || s[0] == '+' {
s = s[1:]
if len(s) < 1 {
return 0, errMissingDigitsAfterSign
}
}
var pn = int8(p)
var d int8 = -1 // current decimal position
var n int64 // output
for _, ch := range s {
if d == pn {
break
}
if ch == sep {
if d != -1 {
return 0, errMultipleDots
}
d = 0
continue
}
ch -= '0'
if ch > 9 {
return 0, errBadDigit
}
n = n*10 + int64(ch)
if d != -1 {
d++
}
}
// fill rest of 0
if d == -1 {
d = 0
}
for i := d; i < pn; i++ {
n = n * 10
}
if s0[0] == '-' {
n = -n
}
return n, nil
}