flyingmutant / rapid

Rapid is a modern Go property-based testing library
https://pkg.go.dev/pgregory.net/rapid
Mozilla Public License 2.0
579 stars 25 forks source link

Big.Int Generator #23

Closed JekaMas closed 3 years ago

JekaMas commented 3 years ago

Thank you for the great tool!

Could you help me? I'm trying to write a big.Int and big.Int range generator, what is the best way to do that? I'm trying it as an external code (if it worked fine, will push the PR).

flyingmutant commented 3 years ago

Thanks for the kind words!

As for unbounded generator, I think something like

rapid.Custom(func(t *rapid.T) *big.Int {
    b := rapid.SliceOf(rapid.Byte()).Draw(t, "b").([]byte)
    i := new(big.Int).SetBytes(b)
    neg := rapid.Bool().Draw(t, "neg").(bool)
    if neg {
        return i.Neg(i)
    }
    return i
})

should do the trick: https://play.golang.org/p/_JD0lf8oZAx

Bounded generator is a bit more tricky, and probably should look like rapid.genIntRange function: we limit the number of generated bytes based on the bounds (rounded up to the nearest power of 2), and then filter out the out-of-bounds numbers.

As for PR -- I think I'd prefer to add these myself (someday); it will probably be easier for me to do it that way.

JekaMas commented 3 years ago

Thanks! By the time I've decided to stick with a partial solution for uint256 - https://play.golang.org/p/E6Y9lM6_720