mirror of
https://github.com/kemko/nomad.git
synced 2026-01-06 18:35:44 +03:00
pointer: add Merge helper function for merging pointers (#15499)
This PR adds Merge() helper function for choosing which value of two pointers to use during a larger merge operation. If 'next' is not nil, use that value, otherwise use the 'previous' value.
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user