go-json/decode_slice.go

74 lines
1.6 KiB
Go
Raw Normal View History

2020-04-25 13:55:05 +03:00
package json
import (
"errors"
"reflect"
"unsafe"
)
type sliceDecoder struct {
elemType *rtype
valueDecoder decoder
size uintptr
}
func newSliceDecoder(dec decoder, elemType *rtype, size uintptr) *sliceDecoder {
return &sliceDecoder{
valueDecoder: dec,
elemType: elemType,
size: size,
}
}
//go:linkname copySlice reflect.typedslicecopy
func copySlice(elemType *rtype, dst, src reflect.SliceHeader) int
//go:linkname newArray reflect.unsafe_NewArray
func newArray(*rtype, int) unsafe.Pointer
2020-05-06 20:37:29 +03:00
func (d *sliceDecoder) decode(buf []byte, cursor int, p uintptr) (int, error) {
buflen := len(buf)
2020-04-25 13:55:05 +03:00
for ; cursor < buflen; cursor++ {
switch buf[cursor] {
case ' ', '\n', '\t', '\r':
continue
case '[':
idx := 0
cap := 2
data := uintptr(newArray(d.elemType, cap))
for {
2020-05-06 20:37:29 +03:00
cursor++
2020-04-25 13:55:05 +03:00
if cap <= idx {
src := reflect.SliceHeader{Data: data, Len: idx, Cap: cap}
cap *= 2
data = uintptr(newArray(d.elemType, cap))
dst := reflect.SliceHeader{Data: data, Len: idx, Cap: cap}
copySlice(d.elemType, dst, src)
}
2020-05-06 20:37:29 +03:00
c, err := d.valueDecoder.decode(buf, cursor, data+uintptr(idx)*d.size)
if err != nil {
return 0, err
2020-04-25 13:55:05 +03:00
}
2020-05-06 20:37:29 +03:00
cursor = c
cursor = skipWhiteSpace(buf, cursor)
2020-04-25 13:55:05 +03:00
switch buf[cursor] {
case ']':
*(*reflect.SliceHeader)(unsafe.Pointer(p)) = reflect.SliceHeader{
Data: data,
Len: idx + 1,
Cap: cap,
}
2020-05-06 20:37:29 +03:00
cursor++
return cursor, nil
2020-04-25 13:55:05 +03:00
case ',':
idx++
continue
default:
2020-05-06 20:37:29 +03:00
return 0, errors.New("syntax error slice")
2020-04-25 13:55:05 +03:00
}
}
}
}
2020-05-06 20:37:29 +03:00
return 0, errors.New("unexpected error slice")
2020-04-25 13:55:05 +03:00
}