Skip to content

Commit

Permalink
feat: add utility function for safe pointer dereferencing
Browse files Browse the repository at this point in the history
- Add `FromPtr` function to handle dereferencing pointers with nil checks
- Add tests for `FromPtr` function covering various types and nil pointers

Signed-off-by: appleboy <[email protected]>
  • Loading branch information
appleboy committed Jan 29, 2025
1 parent 1650473 commit 2c8a020
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
15 changes: 15 additions & 0 deletions convert/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,21 @@ func ToPtr[T any](value T) *T {
return &value
}

// FromPtr takes a pointer to a value and returns the value itself.
// If the pointer is nil, it returns the zero value of the type.
//
// T: The type of the value being dereferenced.
// ptr: The pointer to the value.
//
// Returns the value pointed to by the pointer, or the zero value if the pointer is nil.
func FromPtr[T any](ptr *T) T {
if ptr == nil {
var zero T
return zero
}
return *ptr
}

// ConvertBig5ToUTF8 converts a string encoded in Big5 to UTF-8 encoding.
// It takes a string `s` as input and returns the UTF-8 encoded string.
// If an error occurs during the conversion, it prints an error message and returns the original string.
Expand Down
58 changes: 58 additions & 0 deletions convert/convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,61 @@ func TestConvertBig5ToUTF8(t *testing.T) {
})
}
}

func TestFromPtr(t *testing.T) {
tests := []struct {
name string
ptr interface{}
want interface{}
}{
{
name: "int pointer",
ptr: ToPtr(100),
want: 100,
},
{
name: "nil int pointer",
ptr: (*int)(nil),
want: 0,
},
{
name: "string pointer",
ptr: ToPtr("hello"),
want: "hello",
},
{
name: "nil string pointer",
ptr: (*string)(nil),
want: "",
},
{
name: "bool pointer",
ptr: ToPtr(true),
want: true,
},
{
name: "nil bool pointer",
ptr: (*bool)(nil),
want: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
switch ptr := tt.ptr.(type) {
case *int:
if got := FromPtr(ptr); !reflect.DeepEqual(got, tt.want) {
t.Errorf("FromPtr() = %v, want %v", got, tt.want)
}
case *string:
if got := FromPtr(ptr); !reflect.DeepEqual(got, tt.want) {
t.Errorf("FromPtr() = %v, want %v", got, tt.want)
}
case *bool:
if got := FromPtr(ptr); !reflect.DeepEqual(got, tt.want) {
t.Errorf("FromPtr() = %v, want %v", got, tt.want)
}
}
})
}
}

0 comments on commit 2c8a020

Please sign in to comment.