-
Notifications
You must be signed in to change notification settings - Fork 497
/
json_helpers.go
69 lines (61 loc) · 2.06 KB
/
json_helpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// SPDX-License-Identifier: AGPL-3.0-only
// Provenance-includes-location: https://github.com/cortexproject/cortex/blob/master/pkg/chunk/json_helpers.go
// Provenance-includes-license: Apache-2.0
// Provenance-includes-copyright: The Cortex Authors.
package chunk
import (
"unsafe"
jsoniter "github.com/json-iterator/go"
"github.com/prometheus/common/model"
"github.com/prometheus/prometheus/model/labels"
)
func init() {
jsoniter.RegisterTypeDecoderFunc("labels.Labels", decodeLabels)
jsoniter.RegisterTypeDecoderFunc("model.Time", decodeModelTime)
jsoniter.RegisterTypeEncoderFunc("model.Time", encodeModelTime, modelTimeIsEmpty)
}
// Override Prometheus' labels.Labels decoder which goes via a map
func decodeLabels(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
labelsPtr := (*labels.Labels)(ptr)
builder := labels.NewScratchBuilder(10)
iter.ReadMapCB(func(iter *jsoniter.Iterator, key string) bool {
value := iter.ReadString()
builder.Add(key, value)
return true
})
// Labels are always sorted, but earlier Mimir using a map would
// output in any order so we have to sort on read in
builder.Sort()
*labelsPtr = builder.Labels()
}
// Decode via jsoniter's float64 routine is faster than getting the string data and decoding as two integers
func decodeModelTime(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
pt := (*model.Time)(ptr)
f := iter.ReadFloat64()
*pt = model.Time(int64(f * 1000))
}
// Write out the timestamp as an int divided by 1000. This is ~3x faster than converting to a float.
// Adapted from https://github.com/prometheus/prometheus/blob/cc39021b2bb6f829c7a626e4bdce2f338d1b76db/web/api/v1/api.go#L829
func encodeModelTime(ptr unsafe.Pointer, stream *jsoniter.Stream) {
pt := (*model.Time)(ptr)
t := int64(*pt)
if t < 0 {
stream.WriteRaw(`-`)
t = -t
}
stream.WriteInt64(t / 1000)
fraction := t % 1000
if fraction != 0 {
stream.WriteRaw(`.`)
if fraction < 100 {
stream.WriteRaw(`0`)
}
if fraction < 10 {
stream.WriteRaw(`0`)
}
stream.WriteInt64(fraction)
}
}
func modelTimeIsEmpty(_ unsafe.Pointer) bool {
return false
}