From 626ee3faed6d2cdc04bb0f6735a5303efc33b8a3 Mon Sep 17 00:00:00 2001 From: hc-github-team-nomad-core <82989552+hc-github-team-nomad-core@users.noreply.github.com> Date: Thu, 8 Dec 2022 12:09:52 -0500 Subject: [PATCH] backport of commit 8d30bc6537c193231dd07ce453ab0656897f0b94 (#15502) This pull request was automerged via backport-assistant --- helper/pointer/pointer.go | 16 ++++++++++++---- helper/pointer/pointer_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/helper/pointer/pointer.go b/helper/pointer/pointer.go index 0e806c0bbb1..2e3fc8d4119 100644 --- a/helper/pointer/pointer.go +++ b/helper/pointer/pointer.go @@ -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 @@ -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. diff --git a/helper/pointer/pointer_test.go b/helper/pointer/pointer_test.go index fca66483474..4cef8b5d568 100644 --- a/helper/pointer/pointer_test.go +++ b/helper/pointer/pointer_test.go @@ -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) @@ -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) @@ -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 @@ -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) + }) +}