From d4c08a0f8c56ca3124eea64e6b4380975acf3afe Mon Sep 17 00:00:00 2001 From: Sasha Koshka Date: Fri, 9 Aug 2024 23:41:38 -0400 Subject: [PATCH] Add an Optional type to util --- internal/util/util.go | 35 +++++++++++++++++++++++++++-------- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/internal/util/util.go b/internal/util/util.go index 8b28935..260493d 100644 --- a/internal/util/util.go +++ b/internal/util/util.go @@ -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 +}