Skip to content

Commit

Permalink
improved any -> float/complex/int/uint/bool
Browse files Browse the repository at this point in the history
  • Loading branch information
hedzr committed Feb 20, 2024
1 parent 7486b7a commit d2f3d7f
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
17 changes: 15 additions & 2 deletions cvts.go
Original file line number Diff line number Diff line change
Expand Up @@ -249,6 +249,12 @@ func anyToBool(data any) bool {
case bool:
return z
default:
rv := reflect.ValueOf(data)
rv = ref.Rindirect(rv)
if k := rv.Kind(); k == reflect.Bool {
// eg: flag.stringValue (string)
return rv.Bool()
}
return toBool(anyToString(data))
}
}
Expand Down Expand Up @@ -532,6 +538,7 @@ func anyToString(data any) string {
return fmt.Sprint(data)

default:
rv = ref.Rindirect(rv) // *string -> string
if k := rv.Kind(); k == reflect.String {
// eg: flag.stringValue (string)
return rv.String()
Expand Down Expand Up @@ -596,16 +603,22 @@ func anyToComplex[R Complexes](data any) R {
return R(complex(float64(z), 0))

case float64:
return R(complex(float64(z), 0))
return R(complex(z, 0))
case float32:
return R(complex(float32(z), 0))
return R(complex(z, 0))

case string:
return R(mustParseComplex(z))
case fmt.Stringer:
return R(mustParseComplex(z.String()))

default:
rv := reflect.ValueOf(data)
rv = ref.Rindirect(rv) // *string -> string
if k := rv.Kind(); k == reflect.Complex128 || k == reflect.Complex64 {
// eg: flag.complexValue (complex)
return R(rv.Complex())
}
str := fmt.Sprintf("%v", data)
return R(mustParseComplex(str))
}
Expand Down
20 changes: 20 additions & 0 deletions cvts1.go
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,13 @@ func anyToInt(data any) int64 {
return z.UnixNano()

default:
rv := reflect.ValueOf(data)
rv = ref.Rindirect(rv) // *string -> string
if k := rv.Kind(); k >= reflect.Uint || k <= reflect.Uint64 {
return int64(rv.Uint())
} else if k >= reflect.Int || k <= reflect.Int64 {
return rv.Int()
}
return atoi(fmt.Sprint(data))
}

Expand Down Expand Up @@ -353,6 +360,13 @@ func anyToUint(data any) uint64 {
return uint64(z.UnixNano())

default:
rv := reflect.ValueOf(data)
rv = ref.Rindirect(rv) // *string -> string
if k := rv.Kind(); k >= reflect.Uint || k <= reflect.Uint64 {
return rv.Uint()
} else if k >= reflect.Int || k <= reflect.Int64 {
return uint64(rv.Int())
}
return atou(fmt.Sprint(data))
}
}
Expand Down Expand Up @@ -541,6 +555,12 @@ func anyToFloat[R Floats](data any) R {
return R(mustParseFloat(z.String()))

default:
rv := reflect.ValueOf(data)
rv = ref.Rindirect(rv) // *string -> string
if k := rv.Kind(); k == reflect.Float64 || k == reflect.Float32 {
// eg: flag.floatValue (float)
return R(rv.Float())
}
str := fmt.Sprintf("%v", data)
return R(mustParseFloat(str))
}
Expand Down

0 comments on commit d2f3d7f

Please sign in to comment.