1
0
Fork 0
mirror of https://github.com/diamondburned/arikawa.git synced 2024-11-30 18:53:30 +00:00
arikawa/utils/json/option/string.go

52 lines
1.1 KiB
Go
Raw Normal View History

package option
2020-05-11 21:32:22 +00:00
import (
"encoding/json"
)
// ================================ String ================================
// String is the option type for strings.
type String *string
// NewString creates a new String with the value of the passed string.
func NewString(s string) String { return &s }
2020-05-11 21:32:22 +00:00
// ================================ NullableString ================================
// NullableString is a nullable version of a string.
2020-05-13 00:09:43 +00:00
type NullableString = *NullableStringData
2020-05-11 21:32:22 +00:00
2020-05-13 00:09:43 +00:00
type NullableStringData struct {
2020-05-11 21:32:22 +00:00
Val string
Init bool
}
// NullString serializes to JSON null.
2020-05-13 00:09:43 +00:00
var NullString = &NullableStringData{}
2020-05-11 21:32:22 +00:00
// NewNullableString creates a new non-null NullableString with the value of the passed string.
func NewNullableString(v string) NullableString {
2020-05-13 00:09:43 +00:00
return &NullableStringData{
2020-05-11 21:32:22 +00:00
Val: v,
Init: true,
}
}
2020-05-13 00:09:43 +00:00
func (s NullableStringData) MarshalJSON() ([]byte, error) {
2020-05-11 21:32:22 +00:00
if !s.Init {
return []byte("null"), nil
}
2020-05-13 00:09:43 +00:00
return json.Marshal(s.Val)
2020-05-11 21:32:22 +00:00
}
2020-05-13 00:09:43 +00:00
func (s *NullableStringData) UnmarshalJSON(b []byte) error {
2020-05-11 21:32:22 +00:00
if string(b) == "null" {
*s = *NullString
2020-05-11 21:32:22 +00:00
return nil
}
2020-05-22 17:51:15 +00:00
s.Init = true
2020-05-11 21:32:22 +00:00
return json.Unmarshal(b, &s.Val)
}