Skip to content

Commit

Permalink
Merge pull request #146 from projectdiscovery/maint-ptr
Browse files Browse the repository at this point in the history
Adding safe dereferencing helper
  • Loading branch information
Mzack9999 committed May 6, 2023
2 parents f4baa90 + 100ca58 commit 9a7cd71
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.idea
.vscode
*.exe

11 changes: 11 additions & 0 deletions ptr/ptr.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package ptr

// Safe dereferences safely a pointer
// - if the pointer is nil => returns the zero value of the type of the pointer if nil
// - if the pointer is not nil => returns the dereferenced pointer
func Safe[T any](v *T) T {
if v == nil {
return *new(T)
}
return *v
}
36 changes: 36 additions & 0 deletions ptr/ptr_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package ptr

import (
"github.com/stretchr/testify/require"
"testing"
)

func TestSafe(t *testing.T) {
type args[T any] struct {
v *T
}
type testCase[T any] struct {
name string
args args[T]
want T
}
tests := []testCase[int]{
{
name: "struct=>int - NilPointer",
args: args[int]{v: nil},
want: 0,
},
{
name: "struct=>int - NonNilPointer",
args: args[int]{v: new(int)},
want: 0,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := Safe(tt.args.v)
require.Equal(t, tt.want, got, "Safe() = %v, want %v", got, tt.want)
})
}
}

0 comments on commit 9a7cd71

Please sign in to comment.