use GoJay to marshal JSON

GoJay doesn't use reflection to marshal JSON. This allows dramatically
faster encoding, as well as saving a large number of allocations.
This commit is contained in:
Marten Seemann 2020-01-19 19:19:53 +07:00
parent 2e59206a1e
commit 572ef44cf2
7 changed files with 356 additions and 279 deletions

View file

@ -1,19 +1,12 @@
package qlog
import (
"encoding/json"
"fmt"
"github.com/francoispqt/gojay"
"github.com/lucas-clemente/quic-go/internal/protocol"
"github.com/lucas-clemente/quic-go/internal/wire"
)
type versionNumber protocol.VersionNumber
func (v versionNumber) MarshalJSON() ([]byte, error) {
return escapeStr(fmt.Sprintf("%x", v)), nil
}
func transformHeader(hdr *wire.ExtendedHeader) *packetHeader {
return &packetHeader{
PacketNumber: hdr.PacketNumber,
@ -25,30 +18,30 @@ func transformHeader(hdr *wire.ExtendedHeader) *packetHeader {
}
type packetHeader struct {
PacketNumber protocol.PacketNumber `json:"packet_number,string"`
PacketSize protocol.ByteCount `json:"packet_size,omitempty"`
PayloadLength protocol.ByteCount `json:"payload_length,omitempty"`
PacketNumber protocol.PacketNumber
PacketSize protocol.ByteCount
PayloadLength protocol.ByteCount
Version protocol.VersionNumber `json:"version,omitempty"`
SrcConnectionID protocol.ConnectionID `json:"scid,string,omitempty"`
DestConnectionID protocol.ConnectionID `json:"dcid,string,omitempty"`
Version protocol.VersionNumber
SrcConnectionID protocol.ConnectionID
DestConnectionID protocol.ConnectionID
}
func (h packetHeader) MarshalJSON() ([]byte, error) {
type Alias packetHeader
return json.Marshal(&struct {
SrcConnectionIDLen int `json:"scil,string,omitempty"`
SrcConnectionID connectionID `json:"scid,string,omitempty"`
DestConnectionIDLen int `json:"dcil,string,omitempty"`
DestConnectionID connectionID `json:"dcid,string,omitempty"`
Version versionNumber `json:"version,omitempty"`
Alias
}{
Alias: (Alias)(h),
SrcConnectionIDLen: h.SrcConnectionID.Len(),
SrcConnectionID: connectionID(h.SrcConnectionID),
DestConnectionIDLen: h.DestConnectionID.Len(),
DestConnectionID: connectionID(h.DestConnectionID),
Version: versionNumber(h.Version),
})
func (h packetHeader) MarshalJSONObject(enc *gojay.Encoder) {
enc.StringKey("packet_number", toString(int64(h.PacketNumber)))
enc.Int64KeyOmitEmpty("packet_size", int64(h.PacketSize))
enc.Int64KeyOmitEmpty("payload_length", int64(h.PayloadLength))
if h.Version != 0 {
enc.StringKey("version", versionNumber(h.Version).String())
}
if h.SrcConnectionID.Len() > 0 {
enc.StringKey("scil", toString(int64(h.SrcConnectionID.Len())))
enc.StringKey("scid", connectionID(h.SrcConnectionID).String())
}
if h.DestConnectionID.Len() > 0 {
enc.StringKey("dcil", toString(int64(h.DestConnectionID.Len())))
enc.StringKey("dcid", connectionID(h.DestConnectionID).String())
}
}
func (packetHeader) IsNil() bool { return false }