github.com/3JoB/go-json@v0.10.4/internal/decoder/wrapped_string.go (about)

     1  package decoder
     2  
     3  import (
     4  	"errors"
     5  	"unsafe"
     6  
     7  	"github.com/3JoB/go-reflect"
     8  
     9  	"github.com/3JoB/go-json/internal/runtime"
    10  )
    11  
    12  type wrappedStringDecoder struct {
    13  	typ           *runtime.Type
    14  	dec           Decoder
    15  	stringDecoder *stringDecoder
    16  	structName    string
    17  	fieldName     string
    18  	isPtrType     bool
    19  }
    20  
    21  func newWrappedStringDecoder(typ *runtime.Type, dec Decoder, structName, fieldName string) *wrappedStringDecoder {
    22  	return &wrappedStringDecoder{
    23  		typ:           typ,
    24  		dec:           dec,
    25  		stringDecoder: newStringDecoder(structName, fieldName),
    26  		structName:    structName,
    27  		fieldName:     fieldName,
    28  		isPtrType:     typ.Kind() == reflect.Ptr,
    29  	}
    30  }
    31  
    32  func (d *wrappedStringDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Pointer) error {
    33  	bytes, err := d.stringDecoder.decodeStreamByte(s)
    34  	if err != nil {
    35  		return err
    36  	}
    37  	if bytes == nil {
    38  		if d.isPtrType {
    39  			*(*unsafe.Pointer)(p) = nil
    40  		}
    41  		return nil
    42  	}
    43  	b := make([]byte, len(bytes)+1)
    44  	copy(b, bytes)
    45  	if _, err := d.dec.Decode(&RuntimeContext{Buf: b}, 0, depth, p); err != nil {
    46  		return err
    47  	}
    48  	return nil
    49  }
    50  
    51  func (d *wrappedStringDecoder) Decode(ctx *RuntimeContext, cursor, depth int64, p unsafe.Pointer) (int64, error) {
    52  	bytes, c, err := d.stringDecoder.decodeByte(ctx.Buf, cursor)
    53  	if err != nil {
    54  		return 0, err
    55  	}
    56  	if bytes == nil {
    57  		if d.isPtrType {
    58  			*(*unsafe.Pointer)(p) = nil
    59  		}
    60  		return c, nil
    61  	}
    62  	bytes = append(bytes, nul)
    63  	oldBuf := ctx.Buf
    64  	ctx.Buf = bytes
    65  	if _, err := d.dec.Decode(ctx, 0, depth, p); err != nil {
    66  		return 0, err
    67  	}
    68  	ctx.Buf = oldBuf
    69  	return c, nil
    70  }
    71  
    72  func (d *wrappedStringDecoder) DecodePath(ctx *RuntimeContext, cursor, depth int64) ([][]byte, int64, error) {
    73  	return nil, 0, errors.New("json: wrapped string decoder does not support decode path")
    74  }