safecast

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2024 License: MIT Imports: 3 Imported by: 61

README

🪄 go-safecast: safe numbers conversion

Go Report Card GoDoc codecov Code Climate Sourcegraph

go-safecast solves the type conversion issues in Go

In Go, integer type conversion can lead to a silent and unexpected behavior and errors if not handled carefully.

This package helps to convert any number to another, and report an error when if there would be a loss or overflow in the conversion

Usage

package main

import (
  "fmt"
  "math"

  "github.com/ccoveille/go-safecast"
)

func main() {
  var a int

  a = 42
  b, err := safecast.ToUint8(a) // everything is fine
  if err != nil {
    fmt.Println(err)
  }
  fmt.Println(b)
  // Output: 42

  a = 255 + 1
  _, err = safecast.ToUint8(a) // 256 is greater than uint8 maximum value
  if err != nil {
    fmt.Println(err)
    // Output: conversion issue: 256 (int) is greater than 255 (uint8): maximum value for this type exceeded
  }

  a = -1
  _, err = safecast.ToUint8(a) // -1 cannot fit in uint8
  if err != nil {
    fmt.Println(err)
    // Output: conversion issue: -1 (int) is less than 0 (uint8): minimum value for this type exceeded
  }

  str := "\x99" // ASCII code 153 for Trademark symbol
  e := str[0]
  _, err = safecast.ToInt8(e)
  if err != nil {
    fmt.Println(err)
    // Output: conversion issue: 153 (uint8) is greater than 127 (int8): maximum value for this type exceeded
  }
}

Go Playground

Conversion issues

Issues can happen when converting between signed and unsigned integers, or when converting to a smaller integer type.

package main

import "fmt"

func main() {
  var a int64
  a = 42
  b := uint8(a)
  fmt.Println(b) // 42

  a = 255 // this is the math.MaxUint8
  b = uint8(a)
  fmt.Println(b) // 255

  a = 255 + 1
  b = uint8(a)
  fmt.Println(b) // 0 conversion overflow

  a = -1
  b = uint8(a)
  fmt.Println(b) // 255 conversion overflow
}

Go Playground

So you need to adapt your code to write something like this.

package main

import "fmt"

func main() {
  var a int64
  a = 42
  if a < 0 || a > math.MaxUint8 {
    log.Println("overflow") // Output: overflow
  }
  fmt.Println(b) // 42

  a = 255 // this is the math.MaxUint8
  b = uint8(a)
  fmt.Println(b) // 255

  a = 255 + 1
  b = uint8(a)
  if a < 0 || a > math.MaxUint8 {
    log.Println("overflow") // Output: overflow
  }
  fmt.Println(b) // Output: 0

  a = -1
  b = uint8(a)
  if a < 0 || a > math.MaxUint8 {
    log.Println("overflow") // Output: overflow
  }
  fmt.Println(b) // Output:255
}

Go Playground

go-safecast is there to avoid boilerplate copy pasta.

Motivation

The gosec project raised this to my attention when the gosec G115 rule was added

G115: Potential overflow when converting between integer types.

This issue was way more complex than expected, and required multiple fixes.

CWE-190 explains in detail.

But to sum it up, you can face:

  • infinite loop
  • access to wrong resource by id
  • grant access to someone who exhausted their quota

The gosec G115 will now report issues in a lot of project.

Alternatives

Some libraries existed, but they were not able to cover all the use cases.

Documentation

Overview

Example
package main

import (
	"fmt"

	"github.com/ccoveille/go-safecast"
)

func main() {
	var a int

	a = 42
	b, err := safecast.ToUint8(a) // everything is fine
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(b)

	a = 255 + 1
	_, err = safecast.ToUint8(a) // 256 is greater than uint8 maximum value
	if err != nil {
		fmt.Println(err)
	}

	a = -1
	_, err = safecast.ToUint8(a) // -1 cannot fit in uint8
	if err != nil {
		fmt.Println(err)
	}

	str := "\x99" // ASCII code 153 for Trademark symbol
	e := str[0]
	_, err = safecast.ToInt8(e)
	if err != nil {
		fmt.Println(err)
	}

}
Output:
42
conversion issue: 256 (int) is greater than 255 (uint8): maximum value for this type exceeded
conversion issue: -1 (int) is less than 0 (uint8): minimum value for this type exceeded
conversion issue: 153 (uint8) is greater than 127 (int8): maximum value for this type exceeded

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	ErrConversionIssue    = errors.New("conversion issue")
	ErrExceedMaximumValue = errors.New("maximum value for this type exceeded")
	ErrExceedMinimumValue = errors.New("minimum value for this type exceeded")
)

Functions

func ToInt

func ToInt[T Type](i T) (int, error)

ToInt attempts to convert any Type value to an int. If the conversion results in a value outside the range of an int, an ErrConversionIssue error is returned.

Example
package main

import (
	"fmt"
	"math"

	"github.com/ccoveille/go-safecast"
)

func main() {
	a := uint64(42)
	i, err := safecast.ToInt(a)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)

	b := float32(math.MaxFloat32)
	_, err = safecast.ToInt(b)
	if err != nil {
		fmt.Println(err)
	}
}
Output:
42
conversion issue: 3.4028235e+38 (float32) is greater than 9223372036854775807 (int): maximum value for this type exceeded

func ToInt8

func ToInt8[T Type](i T) (int8, error)

ToInt8 attempts to convert any Type value to an int8. If the conversion results in a value outside the range of an int8, an ErrConversionIssue error is returned.

Example
package main

import (
	"fmt"

	"github.com/ccoveille/go-safecast"
)

func main() {
	a := float64(42.42)
	i, err := safecast.ToInt8(a)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)

	a = float64(200.42)
	_, err = safecast.ToInt8(a)
	if err != nil {
		fmt.Println(err)
	}
}
Output:
42
conversion issue: 200.42 (float64) is greater than 127 (int8): maximum value for this type exceeded

func ToInt16

func ToInt16[T Type](i T) (int16, error)

ToInt16 attempts to convert any Type value to an int16. If the conversion results in a value outside the range of an int16, an ErrConversionIssue error is returned.

Example
package main

import (
	"fmt"

	"github.com/ccoveille/go-safecast"
)

func main() {
	a := int32(42)
	i, err := safecast.ToInt16(a)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)

	a = int32(40000)
	_, err = safecast.ToInt16(a)
	if err != nil {
		fmt.Println(err)
	}
}
Output:
42
conversion issue: 40000 (int32) is greater than 32767 (int16): maximum value for this type exceeded

func ToInt32

func ToInt32[T Type](i T) (int32, error)

ToInt32 attempts to convert any Type value to an int32. If the conversion results in a value outside the range of an int32, an ErrConversionIssue error is returned.

Example
package main

import (
	"fmt"
	"math"

	"github.com/ccoveille/go-safecast"
)

func main() {
	a := int(42)
	i, err := safecast.ToInt32(a)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)

	b := uint32(math.MaxInt32) + 1
	_, err = safecast.ToInt32(b)
	if err != nil {
		fmt.Println(err)
	}
}
Output:
42
conversion issue: 2147483648 (uint32) is greater than 2147483647 (int32): maximum value for this type exceeded

func ToInt64

func ToInt64[T Type](i T) (int64, error)

ToInt64 attempts to convert any Type value to an int64. If the conversion results in a value outside the range of an int64, an ErrConversionIssue error is returned.

Example
package main

import (
	"fmt"
	"math"

	"github.com/ccoveille/go-safecast"
)

func main() {
	a := uint64(42)
	i, err := safecast.ToInt64(a)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)

	a = uint64(math.MaxInt64) + 1
	_, err = safecast.ToInt64(a)
	if err != nil {
		fmt.Println(err)
	}
}
Output:
42
conversion issue: 9223372036854775808 (uint64) is greater than 9223372036854775807 (int64): maximum value for this type exceeded

func ToUint

func ToUint[T Type](i T) (uint, error)

ToUint attempts to convert any Type value to an uint. If the conversion results in a value outside the range of an uint, an ErrConversionIssue error is returned.

Example
package main

import (
	"fmt"

	"github.com/ccoveille/go-safecast"
)

func main() {
	a := int8(42)
	i, err := safecast.ToUint(a)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)

	a = int8(-1)
	_, err = safecast.ToUint(a)
	if err != nil {
		fmt.Println(err)
	}
}
Output:
42
conversion issue: -1 (int8) is less than 0 (uint): minimum value for this type exceeded

func ToUint8

func ToUint8[T Type](i T) (uint8, error)

ToUint8 attempts to convert any Type value to an uint8. If the conversion results in a value outside the range of an uint8, an ErrConversionIssue error is returned.

Example
package main

import (
	"fmt"

	"github.com/ccoveille/go-safecast"
)

func main() {
	a := int64(42)
	i, err := safecast.ToUint8(a)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)

	a = int64(-1)
	_, err = safecast.ToUint8(a)
	if err != nil {
		fmt.Println(err)
	}
}
Output:
42
conversion issue: -1 (int64) is less than 0 (uint8): minimum value for this type exceeded

func ToUint16

func ToUint16[T Type](i T) (uint16, error)

ToUint16 attempts to convert any Type value to an uint16. If the conversion results in a value outside the range of an uint16, an ErrConversionIssue error is returned.

Example
package main

import (
	"fmt"

	"github.com/ccoveille/go-safecast"
)

func main() {
	a := int64(42)
	i, err := safecast.ToUint16(a)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)

	a = int64(-1)
	_, err = safecast.ToUint16(a)
	if err != nil {
		fmt.Println(err)
	}
}
Output:
42
conversion issue: -1 (int64) is less than 0 (uint16): minimum value for this type exceeded

func ToUint32

func ToUint32[T Type](i T) (uint32, error)

ToUint32 attempts to convert any Type value to an uint32. If the conversion results in a value outside the range of an uint32, an ErrConversionIssue error is returned.

Example
package main

import (
	"fmt"

	"github.com/ccoveille/go-safecast"
)

func main() {
	a := int16(42)
	i, err := safecast.ToUint32(a)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)

	a = int16(-1)
	_, err = safecast.ToUint32(a)
	if err != nil {
		fmt.Println(err)
	}
}
Output:
42
conversion issue: -1 (int16) is less than 0 (uint32): minimum value for this type exceeded

func ToUint64

func ToUint64[T Type](i T) (uint64, error)

ToUint64 attempts to convert any Type value to an uint64. If the conversion results in a value outside the range of an uint64, an ErrConversionIssue error is returned.

Example
package main

import (
	"fmt"

	"github.com/ccoveille/go-safecast"
)

func main() {
	a := int8(42)
	i, err := safecast.ToUint64(a)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(i)

	a = int8(-1)
	_, err = safecast.ToUint64(a)
	if err != nil {
		fmt.Println(err)
	}
}
Output:
42
conversion issue: -1 (int8) is less than 0 (uint64): minimum value for this type exceeded

Types

type Error added in v1.2.0

type Error struct {
	// contains filtered or unexported fields
}

func (Error) Error added in v1.2.0

func (e Error) Error() string

func (Error) Unwrap added in v1.2.0

func (e Error) Unwrap() []error

type Float added in v1.1.0

type Float interface {
	~float32 | ~float64
}

Float is an alias for the float32 and float64 types.

type Integer added in v1.1.0

type Integer interface {
	Signed | Unsigned
}

Integer is an alias for the all unsigned and signed integers

type Number

type Number interface {
	Integer | Float
}

Number is an alias for all integers and floats TODO: consider using complex, but not sure there is a need

type Signed added in v1.1.0

type Signed interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64
}

Signed is an alias for all signed integers: int, int8, int16, int32, and int64 types.

type Type added in v1.1.0

type Type interface {
	Number
}

Type is an alias for everything that can be converted

type Unsigned added in v1.1.0

type Unsigned interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}

Unsigned is an alias for all unsigned integers: uint, uint8, uint16, uint32, and uint64 types. TODO: support uintpr

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL