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

     1  package dump
     2  
     3  import (
     4  	"context"
     5  	"unsafe"
     6  	"github.com/v2pro/plz/msgfmt/jsonfmt"
     7  	"encoding/json"
     8  )
     9  
    10  type pointerEncoder struct {
    11  	elemEncoder jsonfmt.Encoder
    12  }
    13  
    14  func (encoder *pointerEncoder) Encode(ctx context.Context, space []byte, ptr unsafe.Pointer) []byte {
    15  	space = append(space, `{"__ptr__":"`...)
    16  	ptrStr := ptrToStr(uintptr(ptr))
    17  	space = append(space, ptrStr...)
    18  	space = append(space, `"}`...)
    19  	elem := encoder.elemEncoder.Encode(ctx, nil, *(*unsafe.Pointer)(ptr))
    20  	addrMap := ctx.Value(addrMapKey).(map[string]json.RawMessage)
    21  	addrMap[ptrStr] = json.RawMessage(elem)
    22  	return space
    23  }