Skip to content

Commit

Permalink
chore: add Option.UnwrapOrDefault
Browse files Browse the repository at this point in the history
Change-Id: I21ee5e63573918b2cc55f74c706c2401a52f29a3
  • Loading branch information
andeya committed Nov 17, 2022
1 parent 0dc8b06 commit 0ba8c94
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 3 deletions.
18 changes: 18 additions & 0 deletions examples/option/unwrap_or_default_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package option_test

import (
"testing"
"time"

"github.com/andeya/gust"
"github.com/andeya/gust/valconv"
"github.com/stretchr/testify/assert"
)

func TestOption_UnwrapOrDefault(t *testing.T) {
assert.Equal(t, "car", gust.Some("car").UnwrapOrDefault())
assert.Equal(t, "", gust.None[string]().UnwrapOrDefault())
assert.Equal(t, time.Time{}, gust.None[time.Time]().UnwrapOrDefault())
assert.Equal(t, &time.Time{}, gust.None[*time.Time]().UnwrapOrDefault())
assert.Equal(t, valconv.Ref(&time.Time{}), gust.None[**time.Time]().UnwrapOrDefault())
}
42 changes: 39 additions & 3 deletions option.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gust
import (
"encoding/json"
"fmt"
"reflect"
"unsafe"
)

Expand Down Expand Up @@ -138,12 +139,12 @@ func (o Option[T]) Unwrap() T {
panic(ToErrBox(fmt.Sprintf("call Option[%T].UnwrapErr() on none", t)))
}

// UnwrapOr returns the contained value or a provided default.
func (o Option[T]) UnwrapOr(defaultSome T) T {
// UnwrapOr returns the contained value or a provided fallback value.
func (o Option[T]) UnwrapOr(fallbackValue T) T {
if o.IsSome() {
return o.UnwrapUnchecked()
}
return defaultSome
return fallbackValue
}

// UnwrapOrElse returns the contained value or computes it from a closure.
Expand All @@ -154,6 +155,41 @@ func (o Option[T]) UnwrapOrElse(defaultSome func() T) T {
return defaultSome()
}

// UnwrapOrDefault returns the contained value or a non-nil-pointer zero value.
func (o Option[T]) UnwrapOrDefault() T {
if o.IsSome() {
return o.UnwrapUnchecked()
}
var zero T
_ = initNilPtr(reflect.ValueOf(&zero))
return zero
}

// initNilPtr initializes nil pointer with zero value.
func initNilPtr(v reflect.Value) (done bool) {
for {
kind := v.Kind()
if kind == reflect.Interface {
v = v.Elem()
continue
}
if kind != reflect.Ptr {
return true
}
u := v.Elem()
if u.IsValid() {
v = u
continue
}
if !v.CanSet() {
return false
}
v2 := reflect.New(v.Type().Elem())
v.Set(v2)
v = v.Elem()
}
}

// Take takes the value out of the option, leaving a [`None`] in its place.
func (o Option[T]) Take() Option[T] {
if o.IsNone() {
Expand Down

0 comments on commit 0ba8c94

Please sign in to comment.