Skip to content

Check for integer overflows in Golang using generics

License

Notifications You must be signed in to change notification settings

g-utils/overflow

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

overflow

Check for integer overflows in Golang (Generic)

Install

go get github.com/g-utils/overflow

Usage

import (
  "github.com/g-utils/overflow"
  "math"
)

func main(){
  a, b := math.MaxInt64 - 5, 6
  sum, ok := overflow.Add(a, b)
  if !ok {
    panic("Overflow occured!")
  }
}

Function signatures: https://pkg.go.dev/github.com/g-utils/overflow

package overflow

type Int interface {
	int | int8 | int16 | int32 | int64 | uint | uint8 | uint16 | uint32 | uint64
}

func Add[T Int](a, b T) (T, bool)
func Sub[T Int](a, b T) (T, bool)
func Mul[T Int](a, b T) (T, bool)
func Div[T Int](a, b T) (T, bool)
func Quotient[T Int](a, b T) (T, T, bool)
func Convert[T Int, U Int](a T) (U, bool)

Copyright / License

This is a fork of https://github.com/JohnCGriffin/overflow. Generics were added to Golang in Go 1.18 (2022) and is used in place of build time code generators.

Tests for unsigned integers have also been added from github.com/rwxe/overflow in case my logic is incorrect.

About

Check for integer overflows in Golang using generics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages