Skip to content

Commit

Permalink
Merge pull request #180 from gaissmai/fb-mustnew
Browse files Browse the repository at this point in the history
add inlineable bitset.MustNew
  • Loading branch information
lemire authored Nov 21, 2024
2 parents 417751b + d22d72b commit ecb7330
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
13 changes: 13 additions & 0 deletions bitset.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,19 @@ func New(length uint) (bset *BitSet) {
return bset
}

// MustNew creates a new BitSet with the given length bits.
// It panics if length exceeds the possible capacity or by a lack of memory.
func MustNew(length uint) (bset *BitSet) {
if length >= Cap() {
panic("You are exceeding the capacity")
}

return &BitSet{
length,
make([]uint64, wordsNeeded(length)), // may panic on lack of memory
}
}

// Cap returns the total possible capacity, or number of bits
// that can be stored in the BitSet theoretically. Under 32-bit system,
// it is 4294967295 and under 64-bit system, it is 18446744073709551615.
Expand Down
48 changes: 48 additions & 0 deletions bitset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -420,6 +420,54 @@ func TestNullCount(t *testing.T) {
}
}

func TestMustNew(t *testing.T) {
testCases := []struct {
length uint
nwords int
}{
{
length: 0,
nwords: 0,
},
{
length: 1,
nwords: 1,
},
{
length: 64,
nwords: 1,
},
{
length: 65,
nwords: 2,
},
{
length: 512,
nwords: 8,
},
{
length: 513,
nwords: 9,
},
}

for _, tc := range testCases {
b := MustNew(tc.length)
if len(b.set) != tc.nwords {
t.Errorf("length = %d, len(b.set) got: %d, want: %d", tc.length, len(b.set), tc.nwords)
}
}
}

func TestPanicMustNew(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("length too big should have caused a panic")
}
}()
MustNew(Cap())
}

func TestPanicDifferenceBNil(t *testing.T) {
var b *BitSet
var compare = New(10)
Expand Down

0 comments on commit ecb7330

Please sign in to comment.