Add an Optional type to util

This commit is contained in:
Sasha Koshka 2024-08-09 23:41:38 -04:00
parent 38054a95bb
commit d4c08a0f8c

View File

@ -91,17 +91,11 @@ func (this *Memo[T]) Value () T {
// Invalidate marks the Memo's value as invalid, which will cause it to be
// updated the next time Value is called.
func (this *Memo[T]) Invalidate () {
var zero T
this.cache = zero
this.valid = false
}
// InvalidateTo invalidates the Memo and sets its value. The new value will be
// entirely inaccessible. This is only intended to be used for setting a
// reference to nil
func (this *Memo[T]) InvalidateTo (value T) {
this.Invalidate()
this.cache = value
}
// Cycler stores a value and an accompanying io.Closer. When the value is set,
// the closer associated with the previous value is closed.
type Cycler[T any] struct {
@ -130,3 +124,28 @@ func (this *Cycler[T]) Close () error {
this.closer = nil
return err
}
// Optional is an optional value.
type Optional[T any] struct {
value T
exists bool
}
// Value returns the value and true if the value exists. If not, it returns the
// last set value and false.
func (this *Optional[T]) Value () (T, bool) {
return this.value, this.exists
}
// Set sets the value.
func (this *Optional[T]) Set (value T) {
this.value = value
this.exists = true
}
// Unset unsets the value.
func (this *Optional[T]) Unset () {
var zero T
this.value = zero
this.exists = false
}