github.com/RomiChan/protobuf@v0.1.1-0.20230204044148-2ed269a2e54d/proto/option.go (about)

     1  package proto
     2  
     3  import (
     4  	"unsafe"
     5  )
     6  
     7  type Option[T any] struct {
     8  	some  bool
     9  	value T
    10  }
    11  
    12  func Some[T any](val T) Option[T] {
    13  	return Option[T]{
    14  		some:  true,
    15  		value: val,
    16  	}
    17  }
    18  
    19  func None[T any]() Option[T] {
    20  	return Option[T]{some: false}
    21  }
    22  
    23  func (o Option[T]) IsSome() bool {
    24  	return o.some
    25  }
    26  
    27  func (o Option[T]) IsNone() bool {
    28  	return !o.some
    29  }
    30  
    31  func (o Option[T]) Unwrap() T {
    32  	if o.IsSome() {
    33  		return o.value
    34  	}
    35  	var zero T
    36  	return zero
    37  }
    38  
    39  func (o Option[T]) UnwrapOr(defaultValue T) T {
    40  	if o.IsSome() {
    41  		return o.value
    42  	}
    43  	return defaultValue
    44  }
    45  
    46  func (o *Option[T]) unsafePointer() unsafe.Pointer {
    47  	return unsafe.Pointer(&o.value)
    48  }
    49  
    50  // Bool stores v in a new bool value and returns a pointer to it.
    51  func Bool(v bool) Option[bool] { return Some(v) }
    52  
    53  // Int32 stores v in a new int32 value and returns a pointer to it.
    54  func Int32(v int32) Option[int32] { return Some(v) }
    55  
    56  // Int64 stores v in a new int64 value and returns a pointer to it.
    57  func Int64(v int64) Option[int64] { return Some(v) }
    58  
    59  // Float32 stores v in a new float32 value and returns a pointer to it.
    60  func Float32(v float32) Option[float32] { return Some(v) }
    61  
    62  // Float64 stores v in a new float64 value and returns a pointer to it.
    63  func Float64(v float64) Option[float64] { return Some(v) }
    64  
    65  // Uint32 stores v in a new uint32 value and returns a pointer to it.
    66  func Uint32(v uint32) Option[uint32] { return Some(v) }
    67  
    68  // Uint64 stores v in a new uint64 value and returns a pointer to it.
    69  func Uint64(v uint64) Option[uint64] { return Some(v) }
    70  
    71  // String stores v in a new string value and returns a pointer to it.
    72  func String(v string) Option[string] { return Some(v) }