Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] The checkedAdd method will not return maxInt64 in case of overflow #91

Open
tangwenqiang opened this issue Apr 29, 2024 · 1 comment
Labels
bug Something isn't working

Comments

@tangwenqiang
Copy link

tangwenqiang commented Apr 29, 2024

Description

The checkedAdd will return (maxInt64 - 2) instead of maxInt64 as the comment saying.

(A possible fix could be: ((naiveSum >> 63) ^ 1) => int64((uint64(naiveSum)>>63)^1))

To Reproduce

Steps to reproduce the behavior:
run this test:

func TestCheckedAdd(t *testing.T) {
	var a, b int64
	a = math.MaxInt64
	b = 23
	
	fmt.Println(checkedAdd(a, b))  // output is: 9223372036854775805 
}

Expected behavior

return maxInt64 when overflow.

@tangwenqiang tangwenqiang added the bug Something isn't working label Apr 29, 2024
@maypok86
Copy link
Owner

Hi, yeah, it looks like I made a mistake in two places at once.

It really should have been an unsigned shift. I tried to test the correctness of this function using Ratio but there was an incident with float64 rounding.

hits := math.MaxInt64
requests := math.MaxInt64 - 2
result := float64(hits)/float64(requests)
fmt.Println(result)

Here the result will be exactly 1.0 :(

I'll probably add a fix to the v2.0 release because users are unlikely to be able to notice this bug.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants