2020-05-11 20:43:52 +00:00
|
|
|
package enum
|
2020-05-11 01:19:11 +00:00
|
|
|
|
|
|
|
import "strconv"
|
|
|
|
|
2020-05-11 20:43:52 +00:00
|
|
|
// Null is the value used to represent JSON null.
|
2020-05-11 01:19:11 +00:00
|
|
|
// It should never be used as a value, as it won't get serialized as such.
|
2020-05-11 20:43:52 +00:00
|
|
|
const Null = -1
|
2020-05-11 01:19:11 +00:00
|
|
|
|
2021-05-21 23:36:43 +00:00
|
|
|
// Enum is a nullable version of a uint32.
|
2020-05-11 01:19:11 +00:00
|
|
|
// Enum values should only consist of positive values, as negative values are reserved for internal constants, such as
|
2020-05-11 20:43:52 +00:00
|
|
|
// Null.
|
2021-05-21 23:36:43 +00:00
|
|
|
// This also means that only 31 of the 32 bits will be available for storage.
|
|
|
|
type Enum int32
|
2020-05-11 01:19:11 +00:00
|
|
|
|
|
|
|
// Int8ToJSON converts the passed Enum to a byte slice with it's JSON representation.
|
2020-05-11 20:43:52 +00:00
|
|
|
func ToJSON(i Enum) []byte {
|
|
|
|
if i == Null {
|
2020-05-11 01:19:11 +00:00
|
|
|
return []byte("null")
|
|
|
|
} else {
|
|
|
|
return []byte(strconv.Itoa(int(i)))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Int8FromJSON decodes the Enum stored as JSON src the passed byte slice.
|
2020-05-11 20:43:52 +00:00
|
|
|
func FromJSON(b []byte) (Enum, error) {
|
2020-05-11 01:19:11 +00:00
|
|
|
s := string(b)
|
|
|
|
|
|
|
|
if s == "null" {
|
2020-05-11 20:43:52 +00:00
|
|
|
return Null, nil
|
2020-05-11 01:19:11 +00:00
|
|
|
} else {
|
|
|
|
i, err := strconv.ParseUint(s, 10, 7)
|
|
|
|
return Enum(i), err
|
|
|
|
}
|
|
|
|
}
|