From 3b4c26fa4dbb29cb9413a27949a21bb093765ff6 Mon Sep 17 00:00:00 2001 From: lucarin91 Date: Wed, 18 Sep 2024 15:38:15 +0200 Subject: [PATCH] feat: add new utility functions --- arguments.go | 9 +++++++++ arguments_test.go | 35 +++++++++++++++++++++++++++++++++++ ptr.go | 16 ++++++++++++++++ ptr_test.go | 30 ++++++++++++++++++++++++++++++ 4 files changed, 90 insertions(+) create mode 100644 arguments_test.go create mode 100644 ptr.go create mode 100644 ptr_test.go diff --git a/arguments.go b/arguments.go index 26d09c7..de8ce17 100644 --- a/arguments.go +++ b/arguments.go @@ -8,6 +8,8 @@ package f +import "fmt" + // Must should be used to wrap a call to a function returning a value and an error. // Must returns the value if the errors is nil, or panics otherwise. func Must[T any](val T, err error) T { @@ -16,3 +18,10 @@ func Must[T any](val T, err error) T { } return val } + +// Assert panics if condition is false. +func Assert(condition bool, msg string, args ...any) { + if !condition { + panic(fmt.Sprintf(msg, args...)) + } +} diff --git a/arguments_test.go b/arguments_test.go new file mode 100644 index 0000000..406210c --- /dev/null +++ b/arguments_test.go @@ -0,0 +1,35 @@ +package f_test + +import ( + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + + f "go.bug.st/f" +) + +func TestMust(t *testing.T) { + t.Run("no error", func(t *testing.T) { + assert.Equal(t, 12, f.Must(12, nil)) + }) + + t.Run("error", func(t *testing.T) { + want := fmt.Errorf("this is an error") + assert.PanicsWithValue(t, want.Error(), func() { + f.Must(0, want) + }) + }) +} + +func TestAssert(t *testing.T) { + t.Run("true", func(_ *testing.T) { + f.Assert(true, "should not panic") + }) + + t.Run("false", func(t *testing.T) { + assert.PanicsWithValue(t, "should panic", func() { + f.Assert(false, "should panic") + }) + }) +} diff --git a/ptr.go b/ptr.go new file mode 100644 index 0000000..2fc4793 --- /dev/null +++ b/ptr.go @@ -0,0 +1,16 @@ +package f + +// Ptr returns a pointer to v. +func Ptr[T any](v T) *T { + return &v +} + +// UnwrapOrDefault returns the ptr value if it is not nil, otherwise returns the zero value. +func UnwrapOrDefault[T any](ptr *T) T { + if ptr != nil { + return *ptr + } + + var zero T + return zero +} diff --git a/ptr_test.go b/ptr_test.go new file mode 100644 index 0000000..db79fad --- /dev/null +++ b/ptr_test.go @@ -0,0 +1,30 @@ +package f_test + +import ( + "testing" + + "github.com/stretchr/testify/assert" + + f "go.bug.st/f" +) + +func TestPtr(t *testing.T) { + t.Run("int", func(t *testing.T) { + assert.Equal(t, 12, *f.Ptr(12)) + }) + + t.Run("string", func(t *testing.T) { + assert.Equal(t, "hello", *f.Ptr("hello")) + }) +} + +func TestUnwrapOrDefault(t *testing.T) { + t.Run("not nil", func(t *testing.T) { + given := 12 + assert.Equal(t, 12, f.UnwrapOrDefault(&given)) + }) + + t.Run("nil", func(t *testing.T) { + assert.Equal(t, "", f.UnwrapOrDefault[string](nil)) + }) +}