MCPcopy Create free account
hub / github.com/DeAI-Artist/Linkis / encodeReflect

Function encodeReflect

libs/json/encoder.go:63–116  ·  view source on GitHub ↗
(w io.Writer, rv reflect.Value)

Source from the content-addressed store, hash-verified

61}
62
63func encodeReflect(w io.Writer, rv reflect.Value) error {
64 if !rv.IsValid() {
65 return errors.New("invalid reflect value")
66 }
67
68 // Recursively dereference if pointer.
69 for rv.Kind() == reflect.Ptr {
70 if rv.IsNil() {
71 return writeStr(w, "null")
72 }
73 rv = rv.Elem()
74 }
75
76 // Convert times to UTC.
77 if rv.Type() == timeType {
78 rv = reflect.ValueOf(rv.Interface().(time.Time).Round(0).UTC())
79 }
80
81 // If the value implements json.Marshaler, defer to stdlib directly. Since we've already
82 // dereferenced, we try implementations with both value receiver and pointer receiver. We must
83 // do this after the time normalization above, and thus after dereferencing.
84 if rv.Type().Implements(jsonMarshalerType) {
85 return encodeStdlib(w, rv.Interface())
86 } else if rv.CanAddr() && rv.Addr().Type().Implements(jsonMarshalerType) {
87 return encodeStdlib(w, rv.Addr().Interface())
88 }
89
90 switch rv.Type().Kind() {
91 // Complex types must be recursively encoded.
92 case reflect.Interface:
93 return encodeReflectInterface(w, rv)
94
95 case reflect.Array, reflect.Slice:
96 return encodeReflectList(w, rv)
97
98 case reflect.Map:
99 return encodeReflectMap(w, rv)
100
101 case reflect.Struct:
102 return encodeReflectStruct(w, rv)
103
104 // 64-bit integers are emitted as strings, to avoid precision problems with e.g.
105 // Javascript which uses 64-bit floats (having 53-bit precision).
106 case reflect.Int64, reflect.Int:
107 return writeStr(w, `"`+strconv.FormatInt(rv.Int(), 10)+`"`)
108
109 case reflect.Uint64, reflect.Uint:
110 return writeStr(w, `"`+strconv.FormatUint(rv.Uint(), 10)+`"`)
111
112 // For everything else, defer to the stdlib encoding/json encoder
113 default:
114 return encodeStdlib(w, rv.Interface())
115 }
116}
117
118func encodeReflectList(w io.Writer, rv reflect.Value) error {
119 // Emit nil slices as null.

Callers 5

encodeFunction · 0.85
encodeReflectListFunction · 0.85
encodeReflectMapFunction · 0.85
encodeReflectStructFunction · 0.85
encodeReflectInterfaceFunction · 0.85

Calls 12

writeStrFunction · 0.85
encodeStdlibFunction · 0.85
encodeReflectInterfaceFunction · 0.85
encodeReflectListFunction · 0.85
encodeReflectMapFunction · 0.85
encodeReflectStructFunction · 0.85
IsValidMethod · 0.80
RoundMethod · 0.80
IntMethod · 0.80
UintMethod · 0.80
TypeMethod · 0.65
AddrMethod · 0.45

Tested by

no test coverage detected