github.com/night-codes/go-json@v0.9.15/internal/decoder/wrapped_string.go (about)

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