Skip to content

Commit

Permalink
Fix int/float conversion to bool (hypermodeinc#2893)
Browse files Browse the repository at this point in the history
* fix conversion from int/float to bool to make zero equal to false

* added tests for int/float -> bool conversion

* change convert empty string to boolean false

* update test to account for empty string to bool false

* added truthy value test

* added falsy value test

* simplified tests and added more cases

* refactor tests for legibility and support

* empty binary should be false

* compacted tests a bit except when failure cases are expected

* fixed typo
  • Loading branch information
srfrog authored Jan 22, 2019
1 parent c038947 commit ef404eb
Show file tree
Hide file tree
Showing 2 changed files with 294 additions and 95 deletions.
19 changes: 13 additions & 6 deletions types/conversion.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ func Convert(from Val, toID TypeID) (Val, error) {
val := math.Float64frombits(i)
*res = float64(val)
case BoolID:
if len(data) == 0 {
*res = false
break
}
if data[0] == 0 {
*res = bool(false)
return to, nil
Expand Down Expand Up @@ -116,11 +120,14 @@ func Convert(from Val, toID TypeID) (Val, error) {
case StringID, DefaultID:
*res = vc
case BoolID:
val, err := strconv.ParseBool(vc)
if err != nil {
return to, err
*res = false
if vc != "" {
val, err := strconv.ParseBool(vc)
if err != nil {
return to, err
}
*res = bool(val)
}
*res = bool(val)
case DateTimeID:
t, err := ParseTime(vc)
if err != nil {
Expand Down Expand Up @@ -162,7 +169,7 @@ func Convert(from Val, toID TypeID) (Val, error) {
case FloatID:
*res = float64(vc)
case BoolID:
*res = bool(vc != 1)
*res = bool(vc != 0)
case StringID, DefaultID:
*res = string(strconv.FormatInt(vc, 10))
case DateTimeID:
Expand Down Expand Up @@ -194,7 +201,7 @@ func Convert(from Val, toID TypeID) (Val, error) {
}
*res = int64(vc)
case BoolID:
*res = bool(vc != 1)
*res = bool(vc != 0)
case StringID, DefaultID:
*res = string(strconv.FormatFloat(float64(vc), 'G', -1, 64))
case DateTimeID:
Expand Down
Loading

0 comments on commit ef404eb

Please sign in to comment.