Skip to content

Commit

Permalink
Add safe integer conversion functions
Browse files Browse the repository at this point in the history
  • Loading branch information
omerzi committed Sep 8, 2024
1 parent 8cc9106 commit 671e148
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
8 changes: 8 additions & 0 deletions safeconvert/int.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,11 @@ func Uint64ToInt64(u uint64) (int64, error) {
}
return int64(u), nil
}

// SafeUint64ToInt converts uint64 to int safely, checking for overflow.
func Uint64ToInt(u uint64) (int, error) {
if u > uint64(math.MaxInt) {
return 0, errors.New("integer overflow: uint64 value exceeds max int value")
}
return int(u), nil
}
22 changes: 22 additions & 0 deletions safeconvert/int_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,25 @@ func TestSafeUint64ToInt64(t *testing.T) {
}
}
}

func TestSafeUint64ToInt(t *testing.T) {
tests := []struct {
input uint64
expected int
errExpected bool
}{
{input: 10, expected: 10},
{input: uint64(math.MaxInt), expected: math.MaxInt},
{input: uint64(math.MaxInt) + 1, expected: 0, errExpected: true},
}

for _, test := range tests {
result, err := Uint64ToInt(test.input)
if test.errExpected {
assert.Error(t, err, "Expected an error for input: %d", test.input)
} else {
assert.NoError(t, err, "Did not expect an error for input: %d", test.input)
assert.Equal(t, test.expected, result, "Expected result does not match")
}
}
}

0 comments on commit 671e148

Please sign in to comment.