Library for safe type conversion in Go
The type of int
equals int64
on 64-bit machine in Go.
When you convert int
(int64
) to int32
, int8
or int6
, Your code could have Integer Overflow vulnerability.
In 2019, Kubernetes had the vulnerability. and the vulnerability was found on Security Audit Project by Trail of Bits.
You can use this library to prevent the vulnerability creation.
(This library is inspired by Kubernetes's Security Audit Report by Trail of Bits)
import "github.com/rung/go-safecast"
i := 2147483647
i32, err := safecast.Int32(i) // convert int to int32 in a safe way
if err != nil {
return err
}
The function returns error when the value is out of the 32-bit range.
This library also has safecast.Int16
and safecast.Int8
. You can use the functions in the same way as safecast.Int32
s := "2147483647"
i, err := safecast.Atoi32(s) // convert string to int32 in a safe way
if err != nil {
return err
}
The function returns error when the value is out of the 32-bit range.
This library also has safecast.Atoi16
and safecast.Atoi8
. You can use the functions in the same way as safecast.Atoi32
int32 (32bit signed integer) | int16 (16bit signed integer) | int8 (8bit signed integer) | |
---|---|---|---|
Range | From -2,147,483,648 to 2,147,483,647 | From -32,768 to 32,767 | From -128 to 127 |
Native int32() type conversion doesn't return error when the code cause integer overflow.
Link: Go Playground
This library returns error when the value is out of the 32-bit range.
So you can convert integer in a safe way.
Link: Go Playground