go-json/decode_float.go

53 lines
1.1 KiB
Go
Raw Normal View History

2020-04-24 10:46:12 +03:00
package json
import (
"strconv"
"unsafe"
)
type floatDecoder struct {
op func(uintptr, float64)
}
func newFloatDecoder(op func(uintptr, float64)) *floatDecoder {
return &floatDecoder{op: op}
}
2020-05-23 06:51:09 +03:00
func (d *floatDecoder) decodeByte(buf []byte, cursor int64) ([]byte, int64, error) {
buflen := int64(len(buf))
2020-04-24 10:46:12 +03:00
for ; cursor < buflen; cursor++ {
switch buf[cursor] {
case ' ', '\n', '\t', '\r':
continue
case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
start := cursor
cursor++
for ; cursor < buflen; cursor++ {
tk := int(buf[cursor])
if (int('0') <= tk && tk <= int('9')) || tk == '.' || tk == 'e' || tk == 'E' {
continue
}
break
}
2020-05-06 20:37:29 +03:00
num := buf[start:cursor]
return num, cursor, nil
2020-04-24 10:46:12 +03:00
}
}
2020-05-23 06:51:09 +03:00
return nil, 0, errUnexpectedEndOfJSON("float", cursor)
2020-04-24 10:46:12 +03:00
}
2020-05-23 06:51:09 +03:00
func (d *floatDecoder) decode(buf []byte, cursor int64, p uintptr) (int64, error) {
2020-05-06 20:37:29 +03:00
bytes, c, err := d.decodeByte(buf, cursor)
2020-04-24 10:46:12 +03:00
if err != nil {
2020-05-06 20:37:29 +03:00
return 0, err
2020-04-24 10:46:12 +03:00
}
2020-05-06 20:37:29 +03:00
cursor = c
2020-04-24 10:46:12 +03:00
s := *(*string)(unsafe.Pointer(&bytes))
f64, err := strconv.ParseFloat(s, 64)
if err != nil {
2020-05-06 20:37:29 +03:00
return 0, err
2020-04-24 10:46:12 +03:00
}
d.op(p, f64)
2020-05-06 20:37:29 +03:00
return cursor, nil
2020-04-24 10:46:12 +03:00
}