Skip to content

Commit

Permalink
backport of commit 8d30bc6 (#15502)
Browse files Browse the repository at this point in the history
This pull request was automerged via backport-assistant
  • Loading branch information
hc-github-team-nomad-core authored and tgross committed Feb 14, 2023
1 parent f464aca commit 626ee3f
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
16 changes: 12 additions & 4 deletions helper/pointer/pointer.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ import (
"golang.org/x/exp/constraints"
)

// Primitive represents basic types that are safe to do basic comparisons by
// pointer dereference (checking nullity first).
type Primitive interface {
constraints.Ordered | bool
}

// Of returns a pointer to a.
func Of[A any](a A) *A {
return &a
Expand All @@ -19,10 +25,12 @@ func Copy[A any](a *A) *A {
return &na
}

// Primitive represents basic types that are safe to do basic comparisons by
// pointer dereference (checking nullity first).
type Primitive interface {
constraints.Ordered // just so happens to be the types we want
// Merge will return Copy(next) if next is not nil, otherwise return Copy(previous).
func Merge[P Primitive](previous, next *P) *P {
if next != nil {
return Copy(next)
}
return Copy(previous)
}

// Eq returns whether a and b are equal in underlying value.
Expand Down
27 changes: 27 additions & 0 deletions helper/pointer/pointer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ import (
"testing"
"time"

"github.com/hashicorp/nomad/ci"
"github.com/shoenig/test/must"
)

func Test_Of(t *testing.T) {
ci.Parallel(t)

s := "hello"
sPtr := Of(s)

Expand All @@ -19,6 +22,8 @@ func Test_Of(t *testing.T) {
}

func Test_Copy(t *testing.T) {
ci.Parallel(t)

orig := Of(1)
dup := Copy(orig)
orig = Of(7)
Expand All @@ -27,6 +32,8 @@ func Test_Copy(t *testing.T) {
}

func Test_Compare(t *testing.T) {
ci.Parallel(t)

t.Run("int", func(t *testing.T) {
a := 1
b := 2
Expand Down Expand Up @@ -65,3 +72,23 @@ func Test_Compare(t *testing.T) {
must.True(t, Eq(n, nil))
})
}

func Test_Merge(t *testing.T) {
ci.Parallel(t)

a := 1
b := 2

ptrA := &a
ptrB := &b

t.Run("exists", func(t *testing.T) {
result := Merge(ptrA, ptrB)
must.Eq(t, 2, *result)
})

t.Run("nil", func(t *testing.T) {
result := Merge(ptrA, nil)
must.Eq(t, 1, *result)
})
}

0 comments on commit 626ee3f

Please sign in to comment.