-
Notifications
You must be signed in to change notification settings - Fork 30
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #146 from projectdiscovery/maint-ptr
Adding safe dereferencing helper
- Loading branch information
Showing
3 changed files
with
51 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
.idea | ||
.vscode | ||
*.exe | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
}) | ||
} | ||
} |