Skip to content

Commit

Permalink
feat: Support conversion from and to string and boolean
Browse files Browse the repository at this point in the history
  • Loading branch information
ccoVeille committed Dec 14, 2024
1 parent 95859b3 commit ce42bea
Show file tree
Hide file tree
Showing 3 changed files with 507 additions and 147 deletions.
44 changes: 44 additions & 0 deletions conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
package safecast

import (
"fmt"
"math"
"strconv"
"strings"
)

func Convert[NumOut Number](orig any) (converted NumOut, err error) {
Expand Down Expand Up @@ -35,6 +38,13 @@ func Convert[NumOut Number](orig any) (converted NumOut, err error) {
return convertFromNumber[NumOut](v)
case float64:
return convertFromNumber[NumOut](v)
case bool:
if v {
return NumOut(1), nil
}
return NumOut(0), nil
case string:
return convertFromString[NumOut](v)
}

return 0, ErrConversionIssue
Expand Down Expand Up @@ -88,6 +98,40 @@ func convertFromNumber[NumOut Number, NumIn Number](orig NumIn) (converted NumOu
}
}

func convertFromString[NumOut Number](s string) (converted NumOut, err error) {
s = strings.TrimSpace(s)

if b, err := strconv.ParseBool(s); err == nil {
if b {
return NumOut(1), nil
}
return NumOut(0), nil
}

if strings.Contains(s, ".") {
o, err := strconv.ParseFloat(s, 64)
if err != nil {
return 0, fmt.Errorf("%w: cannot convert %v to %T", ErrConversionIssue, s, converted)
}
return convertFromNumber[NumOut](o)
}

if s, found := strings.CutPrefix(s, "-"); found {
o, err := strconv.ParseInt(s, 0, 64)
if err != nil || o < 0 {
return 0, fmt.Errorf("%w: cannot convert %v to %T", ErrConversionIssue, s, converted)
}

return convertFromNumber[NumOut](-o)
}

o, err := strconv.ParseUint(s, 0, 64)
if err != nil {
return 0, fmt.Errorf("%w: cannot convert %v to %T", ErrConversionIssue, s, converted)
}
return convertFromNumber[NumOut](o)
}

// ToInt attempts to convert any [Type] value to an int.
// If the conversion results in a value outside the range of an int,
// an [ErrConversionIssue] error is returned.
Expand Down
Loading

0 comments on commit ce42bea

Please sign in to comment.