github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/helper/pointer/pointer.go (about)

     1  // Package pointer provides helper functions related to Go pointers.
     2  package pointer
     3  
     4  import (
     5  	"golang.org/x/exp/constraints"
     6  )
     7  
     8  // Primitive represents basic types that are safe to do basic comparisons by
     9  // pointer dereference (checking nullity first).
    10  type Primitive interface {
    11  	constraints.Ordered | bool
    12  }
    13  
    14  // Of returns a pointer to a.
    15  func Of[A any](a A) *A {
    16  	return &a
    17  }
    18  
    19  // Copy returns a new pointer to a.
    20  func Copy[A any](a *A) *A {
    21  	if a == nil {
    22  		return nil
    23  	}
    24  	na := *a
    25  	return &na
    26  }
    27  
    28  // Merge will return Copy(next) if next is not nil, otherwise return Copy(previous).
    29  func Merge[P Primitive](previous, next *P) *P {
    30  	if next != nil {
    31  		return Copy(next)
    32  	}
    33  	return Copy(previous)
    34  }
    35  
    36  // Eq returns whether a and b are equal in underlying value.
    37  //
    38  // May only be used on pointers to primitive types, where the comparison is
    39  // guaranteed to be sensible. For complex types (i.e. structs) consider implementing
    40  // an Equal method.
    41  func Eq[P Primitive](a, b *P) bool {
    42  	if a == nil || b == nil {
    43  		return a == b
    44  	}
    45  	return *a == *b
    46  }