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

     1  package option
     2  
     3  import (
     4  	"strconv"
     5  
     6  	"github.com/diamondburned/arikawa/v2/discord"
     7  )
     8  
     9  // ================================ Seconds ================================
    10  
    11  // Seconds is the option type for discord.Seconds.
    12  type Seconds = *discord.Seconds
    13  
    14  // ZeroSeconds are 0 Seconds.
    15  var ZeroSeconds = NewSeconds(0)
    16  
    17  // NewString creates a new Seconds with the value of the passed discord.Seconds.
    18  func NewSeconds(s discord.Seconds) Seconds { return &s }
    19  
    20  // ================================ Color ================================
    21  
    22  // Color is the option type for discord.Color.
    23  type Color = *discord.Color
    24  
    25  // NewString creates a new Color with the value of the passed discord.Color.
    26  func NewColor(s discord.Color) Color { return &s }
    27  
    28  // ================================ NullableColor ================================
    29  
    30  // Nullable is a nullable version of discord.Color.
    31  type NullableColor = *NullableColorData
    32  
    33  type NullableColorData struct {
    34  	Val  discord.Color
    35  	Init bool
    36  }
    37  
    38  // NullColor serializes to JSON null.
    39  var NullColor = &NullableColorData{}
    40  
    41  // NewNullableColor creates a new non-null NullableColor using the value of the
    42  // passed discord.Color.
    43  func NewNullableColor(v discord.Color) NullableColor {
    44  	return &NullableColorData{
    45  		Val:  v,
    46  		Init: true,
    47  	}
    48  }
    49  
    50  func (i NullableColorData) MarshalJSON() ([]byte, error) {
    51  	if !i.Init {
    52  		return []byte("null"), nil
    53  	}
    54  	return []byte(strconv.FormatUint(uint64(i.Val), 10)), nil
    55  }
    56  
    57  func (i *NullableColorData) UnmarshalJSON(json []byte) error {
    58  	s := string(json)
    59  
    60  	if s == "null" {
    61  		*i = *NullColor
    62  		return nil
    63  	}
    64  
    65  	v, err := strconv.ParseUint(s, 10, 32)
    66  
    67  	i.Val = discord.Color(v)
    68  	i.Init = true
    69  
    70  	return err
    71  }