go-json/internal/decoder/wrapped_string.go

74 lines
1.7 KiB
Go
Raw Normal View History

2021-06-03 12:49:01 +03:00
package decoder
2020-08-20 06:38:50 +03:00
import (
2022-11-28 21:55:56 +03:00
"fmt"
2021-02-16 05:46:00 +03:00
"reflect"
"unsafe"
2021-06-03 12:49:01 +03:00
"github.com/goccy/go-json/internal/runtime"
)
2020-11-19 06:47:42 +03:00
2020-08-20 06:38:50 +03:00
type wrappedStringDecoder struct {
2021-06-03 12:49:01 +03:00
typ *runtime.Type
2021-06-03 13:10:17 +03:00
dec Decoder
2020-08-20 06:38:50 +03:00
stringDecoder *stringDecoder
structName string
fieldName string
2021-02-16 05:46:00 +03:00
isPtrType bool
2020-08-20 06:38:50 +03:00
}
2021-06-03 13:10:17 +03:00
func newWrappedStringDecoder(typ *runtime.Type, dec Decoder, structName, fieldName string) *wrappedStringDecoder {
2020-08-20 06:38:50 +03:00
return &wrappedStringDecoder{
2021-02-16 05:46:00 +03:00
typ: typ,
2020-08-20 06:38:50 +03:00
dec: dec,
stringDecoder: newStringDecoder(structName, fieldName),
structName: structName,
fieldName: fieldName,
2021-02-16 05:46:00 +03:00
isPtrType: typ.Kind() == reflect.Ptr,
2020-08-20 06:38:50 +03:00
}
}
2021-06-03 12:49:01 +03:00
func (d *wrappedStringDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error {
2020-08-20 06:38:50 +03:00
bytes, err := d.stringDecoder.decodeStreamByte(s)
if err != nil {
return err
}
2021-02-16 05:46:00 +03:00
if bytes == nil {
if d.isPtrType {
*(*unsafe.Pointer)(p) = nil
}
return nil
}
2020-12-05 16:27:33 +03:00
b := make([]byte, len(bytes)+1)
copy(b, bytes)
2021-06-04 19:08:27 +03:00
if _, err := d.dec.Decode(&RuntimeContext{Buf: b}, 0, depth, p); err != nil {
2020-12-05 16:27:33 +03:00
return err
2020-08-20 06:38:50 +03:00
}
return nil
}
2021-06-04 19:08:27 +03:00
func (d *wrappedStringDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) {
bytes, c, err := d.stringDecoder.decodeByte(ctx.Buf, cursor)
2020-08-20 06:38:50 +03:00
if err != nil {
return 0, err
}
2021-02-16 05:46:00 +03:00
if bytes == nil {
if d.isPtrType {
*(*unsafe.Pointer)(p) = nil
}
return c, nil
}
2020-08-20 06:38:50 +03:00
bytes = append(bytes, nul)
2021-06-05 10:00:17 +03:00
oldBuf := ctx.Buf
ctx.Buf = bytes
2021-06-04 19:08:27 +03:00
if _, err := d.dec.Decode(ctx, 0, depth, p); err != nil {
2020-08-20 06:38:50 +03:00
return 0, err
}
2021-06-05 10:00:17 +03:00
ctx.Buf = oldBuf
2020-08-20 06:38:50 +03:00
return c, nil
}
2022-11-28 21:55:56 +03:00
func (d *wrappedStringDecoder) DecodePath(ctx *RuntimeContext, cursor, depth int64) ([][]byte, int64, error) {
return nil, 0, fmt.Errorf("json: wrapped string decoder does not support decode path")
}