Avoid accidental overflow of numbers during go type conversions (e.g instead of shorter := bigger.(int8)
type conversions use shorter := safecast.MustConvert[int8](bigger)
.
Safecast allows you to safely convert between numeric types in Go and return errors (or panic when using the Must*
variants) when the cast would result in a loss of precision, range or sign.
See https://pkg.go.dev/fortio.org/safecast for docs and example. This is usable from any go with generics (1.18 or later) though our CI uses the latest go.
safecast
is about avoiding gosec G115 and CWE-190: Integer Overflow or Wraparound class of overflow and loss of precision bugs, extended to float64/float32 issues.
Credit for the idea (and a finding a bug in the first implementation) goes to @ccoVeille, Please see https://github.com/ccoVeille/go-safecast for an different style API and implementation to pick whichever fits your style best.