generated from WillAbides/goproject-tmpl
-
Notifications
You must be signed in to change notification settings - Fork 6
/
fp.go
470 lines (425 loc) · 8.67 KB
/
fp.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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
package fp
import (
"fmt"
"math"
)
var (
errSyntax = fmt.Errorf("syntax error")
errRange = fmt.Errorf("number out of float64 range")
)
// ParseJSONFloatPrefix is a bit like strconv.ParseFloat but it deals in byte slices instead of strings and
// has everything not needed for json stripped out.
func ParseJSONFloatPrefix(data []byte) (f float64, n int, err error) {
var mantissa uint64
var exp int
var neg, trunc, ok bool
mantissa, exp, neg, trunc, n, ok = readFloat(data)
if !ok {
return 0, 0, errSyntax
}
// to match json behavior: a '.' at the end of the parsed data is an error.
if n > 0 && data[n-1] == '.' {
return 0, 0, errSyntax
}
// Try pure floating-point arithmetic conversion, and if that fails,
// the Eisel-Lemire algorithm.
if !trunc {
if f2, ok := atof64exact(mantissa, exp, neg); ok {
return f2, n, nil
}
}
if f2, ok := eiselLemire64(mantissa, exp, neg); ok {
if !trunc {
return f2, n, nil
}
// Even if the mantissa was truncated, we may
// have found the correct result. Confirm by
// converting the upper mantissa bound.
fUp, ok := eiselLemire64(mantissa+1, exp, neg)
if ok && f2 == fUp {
return f2, n, nil
}
}
// Slow fallback.
var d decimal
if !d.set(data[:n]) {
return 0, n, errSyntax
}
b, ovf := d.floatBits()
f = math.Float64frombits(b)
if ovf {
err = errRange
}
if err != nil {
return 0, n, err
}
return f, n, err
}
// readFloat reads a decimal mantissa and exponent from a float
// string representation in s; the number may be followed by other characters.
// readFloat reports the number of bytes consumed (i), and whether the number
// is valid (ok).
//
//nolint:gocyclo // yep...it's complex
func readFloat(data []byte) (mantissa uint64, exp int, neg, trunc bool, p int, ok bool) {
pe := len(data)
if pe == 0 {
return 0, 0, false, false, p, false
}
// optional sign
if data[0] == '-' {
neg = true
p++
}
if p == pe {
return 0, 0, false, false, p, false
}
const maxMantDigits = 19 // 10^19 fits in uint64
sawdot := false
sawdigits := false
nd := 0
ndMant := 0
dp := 0
// first digit
switch data[p] {
case '.':
return mantissa, 0, neg, trunc, p, false
case '0':
sawdigits = true
nd++
ndMant++
case '1', '2', '3', '4', '5', '6', '7', '8', '9':
sawdigits = true
mantissa += uint64(data[p] - '0')
nd++
ndMant++
default:
goto finishUp
}
p++
if p == pe {
goto finishUp
}
// second digit
switch data[p] {
case '.':
sawdot = true
dp = nd
case '0':
if mantissa == 0 {
goto finishUp
}
sawdigits = true
nd++
ndMant++
mantissa *= 10
case '1', '2', '3', '4', '5', '6', '7', '8', '9':
if mantissa == 0 {
goto finishUp
}
sawdigits = true
nd++
ndMant++
mantissa *= 10
mantissa += uint64(data[p] - '0')
default:
goto finishUp
}
p++
for ; p < len(data); p++ {
if digits[data[p]] {
nd++
if ndMant >= maxMantDigits {
trunc = true
continue
}
mantissa *= 10
mantissa += uint64(data[p] - '0')
ndMant++
continue
}
if data[p] == '.' {
if sawdot {
goto finishUp
}
sawdot = true
dp = nd
continue
}
break
}
finishUp:
if !sawdigits {
return mantissa, 0, neg, trunc, p, false
}
if !sawdot {
dp = nd
}
// optional exponent moves decimal point.
// if we read a very large, very long number,
// just be sure to move the decimal point by
// a lot (say, 100000). it doesn't matter if it's
// not the exact number.
if p < len(data) && (data[p] == 'e' || data[p] == 'E') {
if data[p-1] == '.' {
p = 0
return mantissa, 0, neg, trunc, p, false
}
p++
if p >= len(data) {
return mantissa, 0, neg, trunc, p, false
}
esign := 1
if data[p] == '+' {
p++
} else if data[p] == '-' {
p++
esign = -1
}
if p >= len(data) || data[p] < '0' || data[p] > '9' {
return mantissa, 0, neg, trunc, p, false
}
e := 0
for ; p < len(data) && (data[p] >= '0' && data[p] <= '9'); p++ {
if e < 10000 {
e = e*10 + int(data[p]) - '0'
}
}
dp += e * esign
}
if mantissa != 0 {
exp = dp - ndMant
}
return mantissa, exp, neg, trunc, p, true
}
var digits = [256]bool{
'0': true,
'1': true,
'2': true,
'3': true,
'4': true,
'5': true,
'6': true,
'7': true,
'8': true,
'9': true,
}
func (a *decimal) set(data []byte) (ok bool) {
if len(data) == 0 {
return false
}
a.neg = false
a.trunc = false
i := 0
// optional sign
if data[0] == '-' {
a.neg = true
i = 1
}
// digits
sawdot := false
sawdigits := false
for ; i < len(data); i++ {
switch {
case data[i] == '.':
if sawdot {
return false
}
sawdot = true
a.dp = a.nd
continue
case data[i] >= '0' && data[i] <= '9':
sawdigits = true
if data[i] == '0' && a.nd == 0 { // ignore leading zeros
a.dp--
continue
}
if a.nd < len(a.d) {
a.d[a.nd] = data[i]
a.nd++
} else if data[i] != '0' {
a.trunc = true
}
continue
}
break
}
if !sawdigits {
return false
}
if !sawdot {
a.dp = a.nd
}
// optional exponent moves decimal point.
// if we read a very large, very long number,
// just be sure to move the decimal point by
// a lot (say, 100000). it doesn't matter if it's
// not the exact number.
if i < len(data) && (data[i] == 'e' || data[i] == 'E') {
i++
if i >= len(data) {
return false
}
esign := 1
if data[i] == '+' {
i++
} else if data[i] == '-' {
i++
esign = -1
}
if i >= len(data) || data[i] < '0' || data[i] > '9' {
return false
}
e := 0
for ; i < len(data); i++ {
if data[i] < '0' || data[i] > '9' {
break
}
if e < 10000 {
e = e*10 + int(data[i]) - '0'
}
}
a.dp += e * esign
}
if i != len(data) {
return false
}
return true
}
// decimal power of ten to binary power of two.
var powtab = []int{1, 3, 6, 9, 13, 16, 19, 23, 26}
func (a *decimal) floatBits() (b uint64, overflow bool) {
var exp int
var mant uint64
// Zero is always a special case.
if a.nd == 0 {
mant = 0
exp = bias
goto out
}
// Obvious overflow/underflow.
// These bounds are for 64-bit floats.
// Will have to change if we want to support 80-bit floats in the future.
if a.dp > 310 {
goto overflow
}
if a.dp < -330 {
// zero
mant = 0
exp = bias
goto out
}
// Scale by powers of two until in range [0.5, 1.0)
exp = 0
for a.dp > 0 {
var n int
if a.dp >= len(powtab) {
n = 27
} else {
n = powtab[a.dp]
}
a.Shift(-n)
exp += n
}
for a.dp < 0 || a.dp == 0 && a.d[0] < '5' {
var n int
if -a.dp >= len(powtab) {
n = 27
} else {
n = powtab[-a.dp]
}
a.Shift(n)
exp -= n
}
// Our range is [0.5,1) but floating point range is [1,2).
exp--
// Minimum representable exponent is bias+1.
// If the exponent is smaller, move it up and
// adjust a accordingly.
if exp < bias+1 {
n := bias + 1 - exp
a.Shift(-n)
exp += n
}
if exp-bias >= 1<<expbits-1 {
goto overflow
}
// Extract 1+flt.mantbits bits.
a.Shift(int(1 + mantbits))
mant = a.RoundedInteger()
// Rounding might have added a bit; shift down.
if mant == 2<<mantbits {
mant >>= 1
exp++
if exp-bias >= 1<<expbits-1 {
goto overflow
}
}
// Denormalized?
if mant&(1<<mantbits) == 0 {
exp = bias
}
goto out
overflow:
// ±Inf
mant = 0
exp = 1<<expbits - 1 + bias
overflow = true
out:
// Assemble bits.
bits := mant & (uint64(1)<<mantbits - 1)
bits |= uint64((exp-bias)&(1<<expbits-1)) << mantbits
if a.neg {
bits |= 1 << mantbits << expbits
}
return bits, overflow
}
const (
mantbits uint = 52
expbits uint = 11
bias int = -1023
)
// Exact powers of 10.
var float64pow10 = []float64{
1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9,
1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19,
1e20, 1e21, 1e22,
}
// If possible to convert decimal representation to 64-bit float f exactly,
// entirely in floating-point math, do so, avoiding the expense of decimalToFloatBits.
// Three common cases:
// value is exact integer
// value is exact integer * exact power of ten
// value is exact integer / exact power of ten
// These all produce potentially inexact but correctly rounded answers.
func atof64exact(mantissa uint64, exp int, neg bool) (f float64, ok bool) {
if mantissa>>mantbits != 0 {
return
}
f = float64(mantissa)
if neg {
f = -f
}
switch {
case exp == 0:
// an integer.
return f, true
// Exact integers are <= 10^15.
// Exact powers of ten are <= 10^22.
case exp > 0 && exp <= 15+22: // int * 10^k
// If exponent is big but number of digits is not,
// can move a few zeros into the integer part.
if exp > 22 {
f *= float64pow10[exp-22]
exp = 22
}
if f > 1e15 || f < -1e15 {
// the exponent was really too large.
return
}
return f * float64pow10[exp], true
case exp < 0 && exp >= -22: // int / 10^k
return f / float64pow10[-exp], true
}
return
}