Add jsoniter encoder for Labels

Signed-off-by: Bryan Boreham <bjboreham@gmail.com>
This commit is contained in:
Bryan Boreham 2023-07-04 22:59:43 +01:00
parent 54e1046616
commit bb528d4a55

View file

@ -19,6 +19,7 @@ import (
jsoniter "github.com/json-iterator/go" jsoniter "github.com/json-iterator/go"
"github.com/prometheus/prometheus/model/exemplar" "github.com/prometheus/prometheus/model/exemplar"
"github.com/prometheus/prometheus/model/labels"
"github.com/prometheus/prometheus/promql" "github.com/prometheus/prometheus/promql"
"github.com/prometheus/prometheus/util/jsonutil" "github.com/prometheus/prometheus/util/jsonutil"
) )
@ -29,6 +30,7 @@ func init() {
jsoniter.RegisterTypeEncoderFunc("promql.FPoint", marshalFPointJSON, marshalPointJSONIsEmpty) jsoniter.RegisterTypeEncoderFunc("promql.FPoint", marshalFPointJSON, marshalPointJSONIsEmpty)
jsoniter.RegisterTypeEncoderFunc("promql.HPoint", marshalHPointJSON, marshalPointJSONIsEmpty) jsoniter.RegisterTypeEncoderFunc("promql.HPoint", marshalHPointJSON, marshalPointJSONIsEmpty)
jsoniter.RegisterTypeEncoderFunc("exemplar.Exemplar", marshalExemplarJSON, marshalExemplarJSONEmpty) jsoniter.RegisterTypeEncoderFunc("exemplar.Exemplar", marshalExemplarJSON, marshalExemplarJSONEmpty)
jsoniter.RegisterTypeEncoderFunc("labels.Labels", unsafeMarshalLabelsJSON, labelsIsEmpty)
} }
// JSONCodec is a Codec that encodes API responses as JSON. // JSONCodec is a Codec that encodes API responses as JSON.
@ -217,3 +219,28 @@ func marshalExemplarJSON(ptr unsafe.Pointer, stream *jsoniter.Stream) {
func marshalExemplarJSONEmpty(unsafe.Pointer) bool { func marshalExemplarJSONEmpty(unsafe.Pointer) bool {
return false return false
} }
func unsafeMarshalLabelsJSON(ptr unsafe.Pointer, stream *jsoniter.Stream) {
labelsPtr := (*labels.Labels)(ptr)
marshalLabelsJSON(*labelsPtr, stream)
}
func marshalLabelsJSON(lbls labels.Labels, stream *jsoniter.Stream) {
stream.WriteObjectStart()
i := 0
lbls.Range(func(v labels.Label) {
if i != 0 {
stream.WriteMore()
}
i++
stream.WriteString(v.Name)
stream.WriteRaw(`:`)
stream.WriteString(v.Value)
})
stream.WriteObjectEnd()
}
func labelsIsEmpty(ptr unsafe.Pointer) bool {
labelsPtr := (*labels.Labels)(ptr)
return labelsPtr.IsEmpty()
}