Skip to content

Commit

Permalink
math/big: implement Int.TrailingZeroBits
Browse files Browse the repository at this point in the history
Implemented via the underlying nat.trailingZeroBits.

Fixes golang#29578

Change-Id: If9876c5a74b107cbabceb7547bef4e44501f6745
Reviewed-on: https://go-review.googlesource.com/c/go/+/160681
Reviewed-by: Robert Griesemer <[email protected]>
Run-TryBot: Robert Griesemer <[email protected]>
TryBot-Result: Gobot Gobot <[email protected]>
  • Loading branch information
bmkessler authored and mvdan committed Mar 12, 2019
1 parent 14a58d6 commit ef891e1
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/math/big/int.go
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,12 @@ func (x *Int) BitLen() int {
return x.abs.bitLen()
}

// TrailingZeroBits returns the number of consecutive least significant zero
// bits of |x|.
func (x *Int) TrailingZeroBits() uint {
return x.abs.trailingZeroBits()
}

// Exp sets z = x**y mod |m| (i.e. the sign of m is ignored), and returns z.
// If m == nil or m == 0, z = x**y unless y <= 0 then z = 1.
//
Expand Down
25 changes: 25 additions & 0 deletions src/math/big/int_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1335,6 +1335,31 @@ func TestBitSet(t *testing.T) {
}
}

var tzbTests = []struct {
in string
out uint
}{
{"0", 0},
{"1", 0},
{"-1", 0},
{"4", 2},
{"-8", 3},
{"0x4000000000000000000", 74},
{"-0x8000000000000000000", 75},
}

func TestTrailingZeroBits(t *testing.T) {
for i, test := range tzbTests {
in, _ := new(Int).SetString(test.in, 0)
want := test.out
got := in.TrailingZeroBits()

if got != want {
t.Errorf("#%d: got %v want %v", i, got, want)
}
}
}

func BenchmarkBitset(b *testing.B) {
z := new(Int)
z.SetBit(z, 512, 1)
Expand Down

0 comments on commit ef891e1

Please sign in to comment.