AdGuardHome/internal/aghalg/nullbool.go
Eugene Burkov 99ec1d840c Pull request: use mathutil
Merge in DNS/adguard-home from use-mathutil to master

Squashed commit of the following:

commit cfe2c02a7bb727e81fcd91674aa777df37413a8e
Author: Eugene Burkov <E.Burkov@AdGuard.COM>
Date:   Tue Jan 24 18:12:32 2023 +0300

    all: use mathutil
2023-01-24 19:50:19 +03:00

66 lines
1.4 KiB
Go

package aghalg
import (
"bytes"
"encoding/json"
"fmt"
"github.com/AdguardTeam/golibs/mathutil"
)
// NullBool is a nullable boolean. Use these in JSON requests and responses
// instead of pointers to bool.
type NullBool uint8
// NullBool values
const (
NBNull NullBool = iota
NBTrue
NBFalse
)
// String implements the fmt.Stringer interface for NullBool.
func (nb NullBool) String() (s string) {
switch nb {
case NBNull:
return "null"
case NBTrue:
return "true"
case NBFalse:
return "false"
}
return fmt.Sprintf("!invalid NullBool %d", uint8(nb))
}
// BoolToNullBool converts a bool into a NullBool.
func BoolToNullBool(cond bool) (nb NullBool) {
return NBFalse - mathutil.BoolToNumber[NullBool](cond)
}
// type check
var _ json.Marshaler = NBNull
// MarshalJSON implements the json.Marshaler interface for NullBool.
func (nb NullBool) MarshalJSON() (b []byte, err error) {
return []byte(nb.String()), nil
}
// type check
var _ json.Unmarshaler = (*NullBool)(nil)
// UnmarshalJSON implements the json.Unmarshaler interface for *NullBool.
func (nb *NullBool) UnmarshalJSON(b []byte) (err error) {
if len(b) == 0 || bytes.Equal(b, []byte("null")) {
*nb = NBNull
} else if bytes.Equal(b, []byte("true")) {
*nb = NBTrue
} else if bytes.Equal(b, []byte("false")) {
*nb = NBFalse
} else {
return fmt.Errorf("unmarshalling json data into aghalg.NullBool: bad value %q", b)
}
return nil
}