Skip to content

Commit

Permalink
Merge pull request kubernetes#215 from Daimler/tobiasgiese/add-pointe…
Browse files Browse the repository at this point in the history
…r-int

Add int pointer function
  • Loading branch information
k8s-ci-robot authored Aug 2, 2021
2 parents 7f3ee0f + 51e1ef0 commit efc7438
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
18 changes: 18 additions & 0 deletions pointer/pointer.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,24 @@ func AllPtrFieldsNil(obj interface{}) bool {
return true
}

// Int returns a pointer to an int
func Int(i int) *int {
return &i
}

var IntPtr = Int // for back-compat

// IntDeref dereferences the int ptr and returns it if not nil, or else
// returns def.
func IntDeref(ptr *int, def int) int {
if ptr != nil {
return *ptr
}
return def
}

var IntPtrDerefOr = IntDeref // for back-compat

// Int32 returns a pointer to an int32.
func Int32(i int32) *int32 {
return &i
Expand Down
28 changes: 28 additions & 0 deletions pointer/pointer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,34 @@ func TestAllPtrFieldsNil(t *testing.T) {
}
}

func TestInt(t *testing.T) {
val := int(0)
ptr := Int(val)
if *ptr != val {
t.Errorf("expected %d, got %d", val, *ptr)
}

val = int(1)
ptr = Int(val)
if *ptr != val {
t.Errorf("expected %d, got %d", val, *ptr)
}
}

func TestIntDeref(t *testing.T) {
var val, def int = 1, 0

out := IntDeref(&val, def)
if out != val {
t.Errorf("expected %d, got %d", val, out)
}

out = IntDeref(nil, def)
if out != def {
t.Errorf("expected %d, got %d", def, out)
}
}

func TestInt32(t *testing.T) {
val := int32(0)
ptr := Int32(val)
Expand Down

0 comments on commit efc7438

Please sign in to comment.