1
0
Fork 0
mirror of https://github.com/diamondburned/arikawa.git synced 2024-12-10 23:45:42 +00:00
arikawa/utils/json/option/bool.go

61 lines
1.1 KiB
Go
Raw Normal View History

package option
2020-05-11 21:32:22 +00:00
import "strconv"
// ================================ Bool ================================
// Bool is the option type for bool.
type Bool *bool
var (
True = newBool(true)
False = newBool(false)
)
// newBool creates a new Bool with the value of the passed bool.
func newBool(b bool) Bool { return &b }
2020-05-11 21:32:22 +00:00
// ================================ NullableBool ================================
// NullableBool is the nullable type for bool.
2020-05-13 00:09:43 +00:00
type NullableBool = *NullableBoolData
2020-05-11 21:32:22 +00:00
2020-05-13 00:09:43 +00:00
type NullableBoolData struct {
2020-05-11 21:32:22 +00:00
Val bool
Init bool
}
var (
// NullBool serializes to JSON null.
2020-05-13 00:09:43 +00:00
NullBool = &NullableBoolData{}
NullableTrue = &NullableBoolData{
2020-05-11 21:32:22 +00:00
Val: true,
Init: true,
}
2020-05-13 00:09:43 +00:00
NullableFalse = &NullableBoolData{
2020-05-11 21:32:22 +00:00
Val: false,
Init: true,
}
)
2020-05-13 00:09:43 +00:00
func (b NullableBoolData) MarshalJSON() ([]byte, error) {
2020-05-11 21:32:22 +00:00
if !b.Init {
return []byte("null"), nil
}
return []byte(strconv.FormatBool(b.Val)), nil
}
2020-05-13 00:09:43 +00:00
func (b *NullableBoolData) UnmarshalJSON(json []byte) (err error) {
2020-05-11 21:32:22 +00:00
s := string(json)
if s == "null" {
*b = *NullBool
2020-05-11 21:32:22 +00:00
return
}
b.Val, err = strconv.ParseBool(s)
2020-05-22 17:51:15 +00:00
b.Init = true
2020-05-11 21:32:22 +00:00
return
}