| 1 |
//go:build go1.24 |
| 2 |
|
| 3 |
package encoder |
| 4 |
|
| 5 |
import ( |
| 6 |
"reflect" |
| 7 |
"time" |
| 8 |
"unsafe" |
| 9 |
) |
| 10 |
|
| 11 |
// The output of time.Time.MarshalJSON, time.Time being the type of the standard library which is encoded the |
| 12 |
// most, is known: the text of AppendText quoted. It is written by AppendText, into the buffer, without the |
| 13 |
// allocation of the output. The other types of the standard library are called, and their outputs are not checked |
| 14 |
// ( see MarshalerCall.trusted ). |
| 15 |
// |
| 16 |
// time is the one package of the standard library which is imported for its types ( the others are found by their |
| 17 |
// paths, see runtime.IsStdMarshalerType ): it is linked into every program which uses go-json anyway, as context |
| 18 |
// imports it, and AppendText called directly costs less than called by its code, as a method found by reflect is. |
| 19 |
|
| 20 |
var ( |
| 21 |
timeType = reflect.TypeOf(time.Time{}) |
| 22 |
timePtrType = reflect.PointerTo(timeType) |
| 23 |
) |
| 24 |
|
| 25 |
// stdJSONAppender returns the function which writes the output of MarshalJSON of the type of the standard library, |
| 26 |
// or nil if it is called. The receiver is the data word of the interface value ( see MarshalerCall ): the address |
| 27 |
// of a time.Time, for a time.Time and for a *time.Time alike. |
| 28 |
func stdJSONAppender(recv reflect.Type) func([]byte, unsafe.Pointer) ([]byte, bool) { |
| 29 |
if recv != timeType && recv != timePtrType { |
| 30 |
return nil |
| 31 |
} |
| 32 |
return appendTimeJSON |
| 33 |
} |
| 34 |
|
| 35 |
// appendTimeJSON writes what time.Time.MarshalJSON returns: the text of AppendText quoted, which has nothing to |
| 36 |
// escape. AppendText fails when MarshalJSON does, whose error is then the one of the call of MarshalJSON. |
| 37 |
func appendTimeJSON(b []byte, p unsafe.Pointer) ([]byte, bool) { |
| 38 |
out, err := (*time.Time)(p).AppendText(append(b, '"')) |
| 39 |
if err != nil { |
| 40 |
return b, false |
| 41 |
} |
| 42 |
return append(out, '"'), true |
| 43 |
} |