Skip to content

Commit

Permalink
feat(ptr): add RefOrNil
Browse files Browse the repository at this point in the history
  • Loading branch information
leaxoy committed Jul 6, 2023
1 parent 793187d commit 9ad58eb
Showing 1 changed file with 19 additions and 6 deletions.
25 changes: 19 additions & 6 deletions ptr/ptr.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
package ptr

import "github.com/go-board/std/cmp"
import (
"github.com/go-board/std/cmp"
)

func zero[T any]() (v T) { return }

// Ref return reference of value
func Ref[T any](t T) *T { return &t }

// Default return default value of type
func Default[T any]() *T {
return Ref(zero[T]())
// RefOrNil return reference of value if it not the zero value, else return nil
func RefOrNil[T comparable](t T) *T {
if t == zero[T]() {
return nil
}
return &t
}

// ValueOr return value of pointer if not nil, else return default value.
Expand All @@ -28,8 +33,12 @@ func ValueOrZero[T any](v *T) T {
// Compare compares two pointer. If both non-nil, compare underlying data,
// if both nil, return 0, non-nil pointer is always greater than nil pointer.
func Compare[T cmp.Ordered](l, r *T) int {
return CompareBy(l, r, cmp.Compare[T])
}

func CompareBy[T any](l, r *T, cmp func(T, T) int) int {
if l != nil && r != nil {
return cmp.Compare(*l, *r)
return cmp(*l, *r)
}
if l == nil && r == nil {
return 0
Expand All @@ -43,8 +52,12 @@ func Compare[T cmp.Ordered](l, r *T) int {
// Equal test whether two pointer are equal. If both non-nil, test underlying data,
// if both nil, return true, else return false
func Equal[T comparable](l, r *T) bool {
return EqualBy(l, r, cmp.Equal[T])
}

func EqualBy[T any](l, r *T, eq func(T, T) bool) bool {
if l != nil && r != nil {
return *l == *r
return eq(*l, *r)
} else if l == nil && r == nil {
return true
}
Expand Down

0 comments on commit 9ad58eb

Please sign in to comment.