github.com/primecitizens/pcz/std@v0.2.1/core/opt/value.go (about)

     1  // SPDX-License-Identifier: Apache-2.0
     2  // Copyright 2023 The Prime Citizens
     3  
     4  package opt
     5  
     6  import (
     7  	"github.com/primecitizens/pcz/std/core/assert"
     8  )
     9  
    10  func Maybe[T any](value T, hasValue bool) Value[T] {
    11  	if hasValue {
    12  		return Some(value)
    13  	}
    14  
    15  	return Value[T]{}
    16  }
    17  
    18  func Some[T any](v T) Value[T] {
    19  	return Value[T]{
    20  		V: v,
    21  
    22  		some: true,
    23  	}
    24  }
    25  
    26  // Value.
    27  //
    28  // Zero value means None.
    29  type Value[T any] struct {
    30  	V T
    31  
    32  	some bool
    33  }
    34  
    35  func (o *Value[T]) Set(value T) {
    36  	o.V = value
    37  	o.some = true
    38  }
    39  
    40  func (o Value[T]) Get() T {
    41  	if o.some {
    42  		return o.V
    43  	}
    44  
    45  	assert.Throw("no", "value")
    46  	return o.V
    47  }
    48  
    49  func (o *Value[T]) Erase() (hadValue bool) {
    50  	if o == nil {
    51  		return false
    52  	}
    53  
    54  	hadValue = o.some
    55  
    56  	var zero T
    57  	o.some = false
    58  	o.V = zero
    59  	return
    60  }
    61  
    62  func (o *Value[T]) IsNone() bool { return o == nil || !o.some }
    63  func (o *Value[T]) IsSome() bool { return o != nil && o.some }