go.tools/container/intsets: fix compile error on 32-bit platforms.

Also, fix typo.

LGTM=gri
R=gri
CC=golang-codereviews
https://golang.org/cl/99310043
This commit is contained in:
Alan Donovan 2014-05-15 14:03:05 -04:00
parent ce3f450b0d
commit e1b97610f0
3 changed files with 19 additions and 10 deletions

View File

@ -18,9 +18,9 @@ package intsets
// - Add InsertAll(...int), RemoveAll(...int) // - Add InsertAll(...int), RemoveAll(...int)
// - Add 'bool changed' results for {Intersection,Difference}With too. // - Add 'bool changed' results for {Intersection,Difference}With too.
// //
// TODO(adonovan): implement Dense, a sparse bit vector with a similar // TODO(adonovan): implement Dense, a dense bit vector with a similar API.
// API. The space usage would be proportional to Max(), not Len(), // The space usage would be proportional to Max(), not Len(), and the
// and the implementation would be based upon big.Int. // implementation would be based upon big.Int.
import ( import (
"bytes" "bytes"
@ -131,7 +131,7 @@ func (b *block) empty() bool {
func (b *block) len() int { func (b *block) len() int {
var l int var l int
for _, w := range b.bits { for _, w := range b.bits {
l += int(popcount(w)) l += popcount(w)
} }
return l return l
} }
@ -144,7 +144,7 @@ func (b *block) max() int {
// Decrement bi by number of high zeros in last.bits. // Decrement bi by number of high zeros in last.bits.
for i := len(b.bits) - 1; i >= 0; i-- { for i := len(b.bits) - 1; i >= 0; i-- {
if w := b.bits[i]; w != 0 { if w := b.bits[i]; w != 0 {
return bi - int(nlz(w)) - 1 return bi - nlz(w) - 1
} }
bi -= bitsPerWord bi -= bitsPerWord
} }

View File

@ -19,8 +19,8 @@ func init() {
} }
// popcount returns the population count (number of set bits) of x. // popcount returns the population count (number of set bits) of x.
func popcount(x word) word { func popcount(x word) int {
return word(a[byte(x>>(0*8))] + return int(a[byte(x>>(0*8))] +
a[byte(x>>(1*8))] + a[byte(x>>(1*8))] +
a[byte(x>>(2*8))] + a[byte(x>>(2*8))] +
a[byte(x>>(3*8))] + a[byte(x>>(3*8))] +
@ -32,7 +32,7 @@ func popcount(x word) word {
// nlz returns the number of leading zeros of x. // nlz returns the number of leading zeros of x.
// From Hacker's Delight, fig 5.11. // From Hacker's Delight, fig 5.11.
func nlz(x word) word { func nlz(x word) int {
x |= (x >> 1) x |= (x >> 1)
x |= (x >> 2) x |= (x >> 2)
x |= (x >> 4) x |= (x >> 4)

View File

@ -7,8 +7,17 @@ package intsets
import "testing" import "testing"
func TestNLZ(t *testing.T) { func TestNLZ(t *testing.T) {
if x := nlz(0x0000801000000000); x != 16 { // Test the platform-specific edge case.
t.Errorf("bad %d", x) // NB: v must be a var (not const) so that the word() conversion is dynamic.
// Otherwise the compiler will report an error.
v := uint64(0x0000801000000000)
n := nlz(word(v))
want := 32 // (on 32-bit)
if bitsPerWord == 64 {
want = 16
}
if n != want {
t.Errorf("%d-bit nlz(%d) = %d, want %d", bitsPerWord, v, n, want)
} }
} }