Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions goose_std.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,22 @@ func SumAssumeNoOverflow(x uint64, y uint64) uint64 {
return x + y
}

// MulNoOverflow returns true if x * y does not overflow
func MulNoOverflow(x uint64, y uint64) bool {
if x == 0 || y == 0 {
return true
}
return x <= (1<<64-1)/y
}

// MulAssumeNoOverflow returns x * y, `Assume`ing that this does not overflow.
//
// *Use with care* - if the assumption is violated this function will panic.
func MulAssumeNoOverflow(x uint64, y uint64) uint64 {
primitive.Assume(MulNoOverflow(x, y))
return x * y
}

// JoinHandle is a mechanism to wait for a goroutine to finish. Calling `Join()`
// on the handle returned by `Spawn(f)` will wait for f to finish.
type JoinHandle struct {
Expand Down
15 changes: 15 additions & 0 deletions goose_std_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,21 @@ func TestSumAssumeNoOverflow(t *testing.T) {
})
}

func TestMulAssumeNoOverflow(t *testing.T) {
assert := assert.New(t)

assert.Equal(uint64(6), MulAssumeNoOverflow(2, 3))
assert.Equal(uint64(0), MulAssumeNoOverflow(0, 3))
assert.Equal(uint64(1<<64-1), MulAssumeNoOverflow(1<<32-1, 1<<32+1))
assert.Equal(uint64(1<<64-1), MulAssumeNoOverflow(1<<32+1, 1<<32-1))
assert.Panics(func() {
MulAssumeNoOverflow(1<<63, 2)
})
assert.Panics(func() {
MulAssumeNoOverflow(2, 1<<63)
})
}

func TestMultipar(t *testing.T) {
ch := make(chan uint64)
go Multipar(5, func(i uint64) {
Expand Down