From b09c6d56832eb1718c07d74abf3bc6ae3fe4e030 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 28 Apr 2024 14:36:04 +0200 Subject: Adding upstream version 1.1.0. Signed-off-by: Daniel Baumann --- pkg/types/state_type.go | 65 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 pkg/types/state_type.go (limited to 'pkg/types/state_type.go') diff --git a/pkg/types/state_type.go b/pkg/types/state_type.go new file mode 100644 index 0000000..f0cc69a --- /dev/null +++ b/pkg/types/state_type.go @@ -0,0 +1,65 @@ +package types + +import ( + "database/sql/driver" + "encoding" + "encoding/json" + "github.com/icinga/icingadb/internal" + "github.com/pkg/errors" +) + +// StateType specifies a state's hardness. +type StateType uint8 + +// UnmarshalText implements the encoding.TextUnmarshaler interface. +func (st *StateType) UnmarshalText(text []byte) error { + return st.UnmarshalJSON(text) +} + +// UnmarshalJSON implements the json.Unmarshaler interface. +func (st *StateType) UnmarshalJSON(data []byte) error { + var i uint8 + if err := internal.UnmarshalJSON(data, &i); err != nil { + return err + } + + s := StateType(i) + if _, ok := stateTypes[s]; !ok { + return badStateType(data) + } + + *st = s + return nil +} + +// Value implements the driver.Valuer interface. +func (st StateType) Value() (driver.Value, error) { + if v, ok := stateTypes[st]; ok { + return v, nil + } else { + return nil, badStateType(st) + } +} + +// badStateType returns and error about a syntactically, but not semantically valid StateType. +func badStateType(t interface{}) error { + return errors.Errorf("bad state type: %#v", t) +} + +const ( + StateSoft = StateType(0) + StateHard = StateType(1) +) + +// stateTypes maps all valid StateType values to their SQL representation. +var stateTypes = map[StateType]string{ + StateSoft: "soft", + StateHard: "hard", +} + +// Assert interface compliance. +var ( + _ encoding.TextUnmarshaler = (*StateType)(nil) + _ json.Unmarshaler = (*StateType)(nil) + _ driver.Valuer = StateType(0) +) -- cgit v1.2.3