Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions arguments.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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...))
}
}
35 changes: 35 additions & 0 deletions arguments_test.go
Original file line number Diff line number Diff line change
@@ -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")
})
})
}
16 changes: 16 additions & 0 deletions ptr.go
Original file line number Diff line number Diff line change
@@ -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
}
30 changes: 30 additions & 0 deletions ptr_test.go
Original file line number Diff line number Diff line change
@@ -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))
})
}