Repository navigation
Expand file tree
/
Copy pathfloat.go
More file actions
191 lines (165 loc) · 5.31 KB
/
Copy pathfloat.go
File metadata and controls
191 lines (165 loc) · 5.31 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// Copyright (C) NHR@FAU, University Erlangen-Nuremberg.
// All rights reserved. This file is part of cc-lib.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package schema
import (
"errors"
"io"
"math"
"strconv"
cclog "github.com/ClusterCockpit/cc-lib/v2/ccLogger"
)
// Float is a custom float64 type with special handling for NaN values in JSON and GraphQL serialization.
//
// Standard Go encoding/json treats NaN as an error, but in metric data it's common to have missing
// or invalid measurements that should be represented as null in JSON. This type allows NaN values
// to be serialized as JSON null and vice versa, while avoiding the memory overhead of using
// *float64 pointers for every nullable metric value.
//
// Key behaviors:
// - NaN values marshal to JSON null
// - JSON null unmarshals to NaN
// - Regular float values marshal/unmarshal normally
// - GraphQL marshaling follows the same null handling
//
// This is particularly important for time series metric data where missing data points are
// common and need efficient representation.
type Float float64
// FloatArray is an alias for []Float that can be marshaled to JSON more efficiently.
// This type exists to provide optimized JSON marshaling for arrays of Float values.
type FloatArray []Float
var (
NaN Float = Float(math.NaN())
nullAsBytes []byte = []byte("null")
)
func (f Float) IsNaN() bool {
return math.IsNaN(float64(f))
}
func (f Float) Double() float64 {
return float64(f)
}
// ConvertToFloat converts a regular float64 to a Float, treating -1.0 as a sentinel for NaN.
// This is useful when reading from systems that use -1.0 to indicate missing data.
func ConvertToFloat(input float64) Float {
if input == -1.0 {
return NaN
} else {
return Float(input)
}
}
// MarshalJSON implements the json.Marshaler interface for Float.
// NaN values are serialized as JSON null. Regular float values are
// formatted with 2 decimal places using fixed-point notation.
func (f Float) MarshalJSON() ([]byte, error) {
if f.IsNaN() {
return nullAsBytes, nil
}
return strconv.AppendFloat(make([]byte, 0, 10), float64(f), 'f', 2, 64), nil
}
// UnmarshalJSON implements the json.Unmarshaler interface for Float.
// JSON null is deserialized as NaN. Numeric strings are parsed as float64
// values. Returns an error if the input is neither null nor a valid number.
func (f *Float) UnmarshalJSON(input []byte) error {
s := string(input)
if s == "null" {
*f = NaN
return nil
}
val, err := strconv.ParseFloat(s, 64)
if err != nil {
cclog.Warn("Error while parsing custom float")
return err
}
*f = Float(val)
return nil
}
// UnmarshalGQL implements the graphql.Unmarshaler interface.
func (f *Float) UnmarshalGQL(v any) error {
f64, ok := v.(float64)
if !ok {
return errors.New("invalid Float scalar")
}
*f = Float(f64)
return nil
}
// MarshalGQL implements the graphql.Marshaler interface.
// NaN will be serialized to `null`.
func (f Float) MarshalGQL(w io.Writer) {
if f.IsNaN() {
w.Write(nullAsBytes)
} else {
w.Write(strconv.AppendFloat(make([]byte, 0, 10), float64(f), 'f', 2, 64))
}
}
// MarshalJSON implements the json.Marshaler interface for Series.
// It manually builds the JSON output to reduce allocations compared to
// encoding/json. NaN data points are serialized as null. Only used via
// REST-API, not via GraphQL.
func (s *Series) MarshalJSON() ([]byte, error) {
buf := make([]byte, 0, 512+len(s.Data)*8)
buf = append(buf, `{"hostname":"`...)
buf = append(buf, s.Hostname...)
buf = append(buf, '"')
if s.ID != nil {
buf = append(buf, `,"id":"`...)
buf = append(buf, *s.ID...)
buf = append(buf, '"')
}
buf = append(buf, `,"statistics":{"min":`...)
buf = strconv.AppendFloat(buf, s.Statistics.Min, 'f', 2, 64)
buf = append(buf, `,"avg":`...)
buf = strconv.AppendFloat(buf, s.Statistics.Avg, 'f', 2, 64)
buf = append(buf, `,"max":`...)
buf = strconv.AppendFloat(buf, s.Statistics.Max, 'f', 2, 64)
buf = append(buf, '}')
buf = append(buf, `,"data":[`...)
for i := range s.Data {
if i != 0 {
buf = append(buf, ',')
}
if s.Data[i].IsNaN() {
buf = append(buf, `null`...)
} else {
buf = strconv.AppendFloat(buf, float64(s.Data[i]), 'f', 2, 32)
}
}
buf = append(buf, ']', '}')
return buf, nil
}
// ConvertFloatToFloat64 converts a slice of Float values to a slice of float64 values.
// NaN values in the Float slice will remain as NaN in the float64 slice.
func ConvertFloatToFloat64(s []Float) []float64 {
fp := make([]float64, len(s))
for i, val := range s {
fp[i] = float64(val)
}
return fp
}
// GetFloat64ToFloat converts a slice of float64 values to a slice of Float values.
// This is the inverse operation of ConvertFloatToFloat64.
func GetFloat64ToFloat(s []float64) []Float {
fp := make([]Float, len(s))
for i, val := range s {
fp[i] = Float(val)
}
return fp
}
// MarshalJSON implements json.Marshaler for FloatArray.
// It efficiently marshals a slice of Float values, converting NaN to null.
func (fa FloatArray) MarshalJSON() ([]byte, error) {
buf := make([]byte, 0, 2+len(fa)*8)
buf = append(buf, '[')
for i := range fa {
if i != 0 {
buf = append(buf, ',')
}
if fa[i].IsNaN() {
buf = append(buf, `null`...)
} else {
buf = strconv.AppendFloat(buf, float64(fa[i]), 'f', 3, 64)
}
}
buf = append(buf, ']')
return buf, nil
}