summaryrefslogtreecommitdiffstats
path: root/pkg/types/float.go
blob: a4aedd672e363dcbc6b6ea1f33e6d44c9249ae69 (plain)
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
package types

import (
	"bytes"
	"database/sql"
	"database/sql/driver"
	"encoding"
	"encoding/json"
	"github.com/icinga/icingadb/internal"
	"strconv"
)

// Float adds JSON support to sql.NullFloat64.
type Float struct {
	sql.NullFloat64
}

// MarshalJSON implements the json.Marshaler interface.
// Supports JSON null.
func (f Float) MarshalJSON() ([]byte, error) {
	var v interface{}
	if f.Valid {
		v = f.Float64
	}

	return internal.MarshalJSON(v)
}

// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (f *Float) UnmarshalText(text []byte) error {
	parsed, err := strconv.ParseFloat(string(text), 64)
	if err != nil {
		return internal.CantParseFloat64(err, string(text))
	}

	*f = Float{sql.NullFloat64{
		Float64: parsed,
		Valid:   true,
	}}

	return nil
}

// UnmarshalJSON implements the json.Unmarshaler interface.
// Supports JSON null.
func (f *Float) UnmarshalJSON(data []byte) error {
	// Ignore null, like in the main JSON package.
	if bytes.HasPrefix(data, []byte{'n'}) {
		return nil
	}

	if err := internal.UnmarshalJSON(data, &f.Float64); err != nil {
		return err
	}

	f.Valid = true

	return nil
}

// Assert interface compliance.
var (
	_ json.Marshaler           = Float{}
	_ encoding.TextUnmarshaler = (*Float)(nil)
	_ json.Unmarshaler         = (*Float)(nil)
	_ driver.Valuer            = Float{}
	_ sql.Scanner              = (*Float)(nil)
)