Debian Codegraph @

strconv/number.go

raw
1 package strconv
2
3 import (
4 "math"
5 "unicode/utf8"
6 )
7
8 // ParseNumber parses a byte-slice and returns the number it represents and the amount of decimals.
9 // If an invalid character is encountered, it will stop there.
10 func ParseNumber(b []byte, groupSym rune, decSym rune) (int64, int, int) {
11 n, dec := 0, 0
12 sign := int64(1)
13 num := int64(0)
14 hasDecimals := false
15 if 0 < len(b) && b[0] == '-' {
16 sign = -1
17 n++
18 }
19 for n < len(b) {
20 if '0' <= b[n] && b[n] <= '9' {
21 digit := sign * int64(b[n]-'0')
22 if sign == 1 && (math.MaxInt64/10 < num || math.MaxInt64-digit < num*10) {
23 break
24 } else if sign == -1 && (num < math.MinInt64/10 || num*10 < math.MinInt64-digit) {
25 break
26 }
27 num *= 10
28 num += digit
29 if hasDecimals {
30 dec++
31 }
32 n++
33 } else if r, size := utf8.DecodeRune(b[n:]); !hasDecimals && (r == groupSym || r == decSym) {
34 if r == decSym {
35 hasDecimals = true
36 }
37 n += size
38 } else {
39 break
40 }
41 }
42 return num, dec, n
43 }
44
45 // AppendNumber will append an int64 formatted as a number with the given number of decimal digits.
46 func AppendNumber(b []byte, num int64, dec int, groupSize int, groupSym rune, decSym rune) []byte {
47 if dec < 0 {
48 dec = 0
49 }
50 if utf8.RuneLen(groupSym) == -1 {
51 groupSym = '.'
52 }
53 if utf8.RuneLen(decSym) == -1 {
54 decSym = ','
55 }
56
57 sign := int64(1)
58 if num < 0 {
59 sign = -1
60 }
61
62 // calculate size
63 n := LenInt(num)
64 if sign == -1 {
65 n-- // ignore minux sign, add later
66 }
67 if dec < n && 0 < groupSize && groupSym != 0 {
68 n += utf8.RuneLen(groupSym) * (n - dec - 1) / groupSize
69 }
70 if 0 < dec {
71 if n <= dec {
72 n = 1 + dec // zero and decimals
73 }
74 n += utf8.RuneLen(decSym)
75 }
76 if sign == -1 {
77 n++
78 }
79
80 // resize byte slice
81 i := len(b)
82 if cap(b) < i+n {
83 b = append(b, make([]byte, n)...)
84 } else {
85 b = b[:i+n]
86 }
87
88 // print fractional-part
89 i += n - 1
90 if 0 < dec {
91 for 0 < dec {
92 c := byte(sign*(num%10)) + '0'
93 num /= 10
94 b[i] = c
95 dec--
96 i--
97 }
98 i -= utf8.RuneLen(decSym)
99 utf8.EncodeRune(b[i+1:], decSym)
100 }
101
102 // print integer-part
103 if num == 0 {
104 b[i] = '0'
105 if sign == -1 {
106 b[i-1] = '-'
107 }
108 return b
109 }
110 j := 0
111 for num != 0 {
112 if 0 < groupSize && groupSym != 0 && 0 < j && j%groupSize == 0 {
113 i -= utf8.RuneLen(groupSym)
114 utf8.EncodeRune(b[i+1:], groupSym)
115 }
116
117 c := byte(sign*(num%10)) + '0'
118 num /= 10
119 b[i] = c
120 i--
121 j++
122 }
123
124 if sign == -1 {
125 b[i] = '-'
126 }
127 return b
128 }