From 51e1ef05cd486f886515a7625a30bb17a1e5f37c Mon Sep 17 00:00:00 2001 From: Tobias Giese Date: Mon, 2 Aug 2021 17:44:24 +0200 Subject: [PATCH] pointer/pointer.go: add func pointer.Int() Signed-off-by: Tobias Giese --- pointer/pointer.go | 18 ++++++++++++++++++ pointer/pointer_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/pointer/pointer.go b/pointer/pointer.go index 1da6f666..2cab2c58 100644 --- a/pointer/pointer.go +++ b/pointer/pointer.go @@ -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 diff --git a/pointer/pointer_test.go b/pointer/pointer_test.go index 96f2868d..afce4e90 100644 --- a/pointer/pointer_test.go +++ b/pointer/pointer_test.go @@ -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)