|
| 1 | +package plugin |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "math" |
| 6 | + "time" |
| 7 | +) |
| 8 | + |
| 9 | +func (fv *floatValue) UnmarshalJSON(data []byte) error { |
| 10 | + // Create an intermediate struct with a raw message for the value |
| 11 | + aux := struct { |
| 12 | + Timestamp time.Time `json:"timestamp"` |
| 13 | + Value json.RawMessage `json:"value"` |
| 14 | + }{} |
| 15 | + |
| 16 | + if err := json.Unmarshal(data, &aux); err != nil { |
| 17 | + return err |
| 18 | + } |
| 19 | + |
| 20 | + // Set the timestamp |
| 21 | + fv.Timestamp = aux.Timestamp |
| 22 | + |
| 23 | + // Handle the value field specially |
| 24 | + switch string(aux.Value) { |
| 25 | + case `"NaN"`: |
| 26 | + fv.Value = float32(math.NaN()) |
| 27 | + case `"Inf"`, `"Infinity"`: |
| 28 | + fv.Value = float32(math.Inf(1)) |
| 29 | + case `"-Inf"`, `"-Infinity"`: |
| 30 | + fv.Value = float32(math.Inf(-1)) |
| 31 | + default: |
| 32 | + var v float32 |
| 33 | + if err := json.Unmarshal(aux.Value, &v); err != nil { |
| 34 | + return err |
| 35 | + } |
| 36 | + fv.Value = v |
| 37 | + } |
| 38 | + |
| 39 | + return nil |
| 40 | +} |
| 41 | + |
| 42 | +func (dv *doubleValue) UnmarshalJSON(data []byte) error { |
| 43 | + // Create an intermediate struct with a raw message for the value |
| 44 | + aux := struct { |
| 45 | + Timestamp time.Time `json:"timestamp"` |
| 46 | + Value json.RawMessage `json:"value"` |
| 47 | + }{} |
| 48 | + |
| 49 | + if err := json.Unmarshal(data, &aux); err != nil { |
| 50 | + return err |
| 51 | + } |
| 52 | + |
| 53 | + // Set the timestamp |
| 54 | + dv.Timestamp = aux.Timestamp |
| 55 | + |
| 56 | + // Handle the value field specially |
| 57 | + switch string(aux.Value) { |
| 58 | + case `"NaN"`: |
| 59 | + dv.Value = math.NaN() |
| 60 | + case `"Inf"`, `"Infinity"`: |
| 61 | + dv.Value = math.Inf(1) |
| 62 | + case `"-Inf"`, `"-Infinity"`: |
| 63 | + dv.Value = math.Inf(-1) |
| 64 | + default: |
| 65 | + var v float64 |
| 66 | + if err := json.Unmarshal(aux.Value, &v); err != nil { |
| 67 | + return err |
| 68 | + } |
| 69 | + dv.Value = v |
| 70 | + } |
| 71 | + |
| 72 | + return nil |
| 73 | +} |
0 commit comments