Skip to content

Commit

Permalink
feat: support stringer and error as source
Browse files Browse the repository at this point in the history
  • Loading branch information
ccoVeille committed Dec 14, 2024
1 parent ce42bea commit 179c7ad
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
4 changes: 4 additions & 0 deletions conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ func Convert[NumOut Number](orig any) (converted NumOut, err error) {
return NumOut(1), nil
}
return NumOut(0), nil
case fmt.Stringer:
return convertFromString[NumOut](v.String())
case error:
return convertFromString[NumOut](v.Error())
case string:
return convertFromString[NumOut](v)
}
Expand Down
14 changes: 14 additions & 0 deletions conversion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@ import (
"github.com/ccoveille/go-safecast"
)

type anyStringer struct{}

func (anyStringer) String() string {
return "42"
}

type anyError struct{}

func (anyError) Error() string {
return "42"
}

func TestToInt8(t *testing.T) {
t.Run("from int", func(t *testing.T) {
assertInt8OK(t, []caseInt8[int]{
Expand Down Expand Up @@ -1552,6 +1564,8 @@ func TestConvert(t *testing.T) {
"positive string within range": {input: "42", want: 42},
"negative string within range": {input: "-42", want: -42},
"float string within range": {input: "100.0", want: 100},
"stringer": {input: anyStringer{}, want: 42},
"error": {input: anyError{}, want: 42},
} {
t.Run(name, func(t *testing.T) {
got, err := safecast.Convert[int8](tt.input)
Expand Down

0 comments on commit 179c7ad

Please sign in to comment.