2023-07-08 11:21:26 +02:00
|
|
|
package option
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
jsonNull = []byte("null")
|
|
|
|
)
|
|
|
|
|
|
|
|
// Option defines a data structure that logically holds a value or not
|
|
|
|
type Option[A any] struct {
|
2023-07-09 10:21:56 +02:00
|
|
|
isSome bool
|
|
|
|
some A
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// String prints some debug info for the object
|
|
|
|
func (s Option[A]) String() string {
|
2023-07-09 10:21:56 +02:00
|
|
|
if s.isSome {
|
|
|
|
return fmt.Sprintf("Some[%T](%v)", s.some, s.some)
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
2023-07-09 10:21:56 +02:00
|
|
|
return fmt.Sprintf("None[%T]", s.some)
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Format prints some debug info for the object
|
|
|
|
func (s Option[A]) Format(f fmt.State, c rune) {
|
|
|
|
switch c {
|
|
|
|
case 's':
|
|
|
|
fmt.Fprint(f, s.String())
|
|
|
|
default:
|
|
|
|
fmt.Fprint(f, s.String())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s Option[A]) MarshalJSON() ([]byte, error) {
|
2023-07-09 10:21:56 +02:00
|
|
|
if IsSome(s) {
|
|
|
|
return json.Marshal(s.some)
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
2023-07-09 10:21:56 +02:00
|
|
|
return jsonNull, nil
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
|
|
|
|
2023-07-09 10:21:56 +02:00
|
|
|
func (s *Option[A]) UnmarshalJSON(data []byte) error {
|
2023-07-08 11:21:26 +02:00
|
|
|
// decode the value
|
|
|
|
if bytes.Equal(data, jsonNull) {
|
2023-07-09 10:21:56 +02:00
|
|
|
s.isSome = false
|
|
|
|
s.some = *new(A)
|
2023-07-08 11:21:26 +02:00
|
|
|
return nil
|
|
|
|
}
|
2023-07-09 10:21:56 +02:00
|
|
|
s.isSome = true
|
|
|
|
return json.Unmarshal(data, &s.some)
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func IsNone[T any](val Option[T]) bool {
|
2023-07-09 10:21:56 +02:00
|
|
|
return !val.isSome
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func Some[T any](value T) Option[T] {
|
2023-07-09 10:21:56 +02:00
|
|
|
return Option[T]{isSome: true, some: value}
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func Of[T any](value T) Option[T] {
|
|
|
|
return Some(value)
|
|
|
|
}
|
|
|
|
|
|
|
|
func None[T any]() Option[T] {
|
2023-07-09 10:21:56 +02:00
|
|
|
return Option[T]{isSome: false}
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func IsSome[T any](val Option[T]) bool {
|
2023-07-09 10:21:56 +02:00
|
|
|
return val.isSome
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func MonadFold[A, B any](ma Option[A], onNone func() B, onSome func(A) B) B {
|
2023-07-09 10:21:56 +02:00
|
|
|
if IsSome(ma) {
|
|
|
|
return onSome(ma.some)
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
2023-07-09 10:21:56 +02:00
|
|
|
return onNone()
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
func Unwrap[A any](ma Option[A]) (A, bool) {
|
2023-07-09 10:21:56 +02:00
|
|
|
return ma.some, ma.isSome
|
2023-07-08 11:21:26 +02:00
|
|
|
}
|