github.com/diamondburned/arikawa/v2@v2.1.0/utils/json/option/bool.go (about)

     1  package option
     2  
     3  import "strconv"
     4  
     5  // ================================ Bool ================================
     6  
     7  // Bool is the option type for bool.
     8  type Bool *bool
     9  
    10  var (
    11  	True  = newBool(true)
    12  	False = newBool(false)
    13  )
    14  
    15  // newBool creates a new Bool with the value of the passed bool.
    16  func newBool(b bool) Bool { return &b }
    17  
    18  // ================================ NullableBool ================================
    19  
    20  // NullableBool is the nullable type for bool.
    21  type NullableBool = *NullableBoolData
    22  
    23  type NullableBoolData struct {
    24  	Val  bool
    25  	Init bool
    26  }
    27  
    28  var (
    29  	// NullBool serializes to JSON null.
    30  	NullBool     = &NullableBoolData{}
    31  	NullableTrue = &NullableBoolData{
    32  		Val:  true,
    33  		Init: true,
    34  	}
    35  	NullableFalse = &NullableBoolData{
    36  		Val:  false,
    37  		Init: true,
    38  	}
    39  )
    40  
    41  func (b NullableBoolData) MarshalJSON() ([]byte, error) {
    42  	if !b.Init {
    43  		return []byte("null"), nil
    44  	}
    45  	return []byte(strconv.FormatBool(b.Val)), nil
    46  }
    47  
    48  func (b *NullableBoolData) UnmarshalJSON(json []byte) (err error) {
    49  	s := string(json)
    50  
    51  	if s == "null" {
    52  		*b = *NullBool
    53  		return
    54  	}
    55  
    56  	b.Val, err = strconv.ParseBool(s)
    57  	b.Init = true
    58  
    59  	return
    60  }