github.com/v2pro/plz@v0.0.0-20221028024117-e5f9aec5b631/dump/str.go (about)

     1  package dump
     2  
     3  import (
     4  	"context"
     5  	"unsafe"
     6  	"encoding/json"
     7  	"github.com/v2pro/plz/msgfmt/jsonfmt"
     8  	"reflect"
     9  )
    10  
    11  var strEncoderInst = jsonfmt.EncoderOf(reflect.TypeOf(""))
    12  
    13  type stringHeader struct {
    14  	data unsafe.Pointer
    15  	len  int
    16  }
    17  
    18  type stringEncoder struct {
    19  }
    20  
    21  func (encoder *stringEncoder) Encode(ctx context.Context, space []byte, ptr unsafe.Pointer) []byte {
    22  	header := (*stringHeader)(ptr)
    23  	space = append(space, `{"data":{"__ptr__":"`...)
    24  	ptrStr := ptrToStr(uintptr(header.data))
    25  	space = append(space, ptrStr...)
    26  	space = append(space, `"},"len":`...)
    27  	space = jsonfmt.WriteInt64(space, int64(header.len))
    28  	space = append(space, `}`...)
    29  	elem := strEncoderInst.Encode(ctx, nil, ptr)
    30  	if uintptr(header.data) != 0 {
    31  		addrMap := ctx.Value(addrMapKey).(map[string]json.RawMessage)
    32  		addrMap[ptrStr] = json.RawMessage(elem)
    33  	}
    34  	return space
    35  }