cast icon indicating copy to clipboard operation
cast copied to clipboard

Bug: Wrong conversion ToUint64

Open tdrozdovsky opened this issue 2 years ago • 1 comments

...
inValue = "18446744073709551615"
log.Printf("inValue = %v", inValue )
outValue := cast.ToUint64(inValue )
log.Printf("outValue = %v", outValue )
...

Result for v1.4.1:

INFO[2022-06-06T14:01:00+03:00] inValue = 18446744073709551615               
INFO[2022-06-06T14:01:00+03:00] outValue = 18446744073709551615

Result for v1.5.0:

INFO[2022-06-06T14:01:00+03:00] inValue = 18446744073709551615               
INFO[2022-06-06T14:01:00+03:00] outValue = 0

tdrozdovsky avatar Jun 06 '22 11:06 tdrozdovsky

The problem appears to be in the ToUint* functions and was introduced in commit 2b0eb0f724e320b655240e331aef36d1175986c2.

Previously, the code was:

	case string:
		v, err := strconv.ParseUint(s, 0, 0)
		if err == nil {
			return uint(v), nil
		}
		return 0, fmt.Errorf("unable to cast %#v to uint: %s", i, err)

But in that commit it was replaced with:

	case string:
		v, err := strconv.ParseInt(trimZeroDecimal(s), 0, 0)
		if err == nil {
			if v < 0 {
				return 0, errNegativeNotAllowed
			}
			return uint(v), nil
		}
		return 0, fmt.Errorf("unable to cast %#v of type %T to uint", i, i)

All ToUint* functions have this bug (bad copy&paste?).

The previous code should be restored -- the only new addition is trimZeroDecimal(s), which can be added to the old code as well. The check for negative values is also not needed if using ParseUint as before.

abukosek avatar Jun 06 '22 12:06 abukosek