FromWithLength constructor not validating length against slice length
semihbkgr opened this issue · 0 comments
semihbkgr commented
FromWithLength
doesn't validate if the given slice ([]uint64) has enough length to represent the specified length in bits.
b := []uint64{
0b0101010001, 0b010101010,
}
bs := bitset.FromWithLength(1000, b)
fmt.Println(bs.String())
fmt.Println(bs.Len())
bs.Set(200)
The constructor assumes that the bitset length is the specified 1000 bits, but the underlying slice only has 2 elements, which provides a bit capacity of 128 bits which is less than the requested 1000. When attempting to set bit 200, it tries to access the 3rd index in the slice (assuming the slice has 1000/word-size
len at least), resulting in a runtime panic due to out-of-bounds access.
We can possibly address this issue in different ways, such as:
- Panic on insufficient
len
orcap
- Set length based on slice capacity: Adjust the bitset's length to match the capacity of the provided slice, ensuring no out-of-bounds access.
- We can also grow the slice: Allocate a new slice with sufficient capacity to match the requested length and copy the contents of the provided slice into it.