Language: Go
Label: safe
CWE: CWE-1284 \u2014 Improper Validation of Specified Quantity in Input
The product receives input that is expected to specify a quantity (such as size or length), but it does not validate or incorrectly validates that the quantity has the required properties.

Code:
func TestBitfield(t *testing.T) {
	bf, err := NewBitfield(128)
	assertNoError(t, err)
	if bf.OnesBefore(20) != 0 {
		t.Fatal("expected no bits set")
	}
	bf.SetBit(10)
	if bf.OnesBefore(20) != 1 {
		t.Fatal("expected 1 bit set")
	}
	bf.SetBit(12)
	if bf.OnesBefore(20) != 2 {
		t.Fatal("expected 2 bit set")
	}
	bf.SetBit(30)
	if bf.OnesBefore(20) != 2 {
		t.Fatal("expected 2 bit set")
	}
	bf.SetBit(100)
	if bf.OnesBefore(20) != 2 {
		t.Fatal("expected 2 bit set")
	}
	bf.UnsetBit(10)
	if bf.OnesBefore(20) != 1 {
		t.Fatal("expected 1 bit set")
	}

	bint := new(big.Int).SetBytes(bf.Bytes())
	for i := 0; i < 128; i++ {
		if bf.Bit(i) != (bint.Bit(i) == 1) {
			t.Fatalf("expected bit %d to be %v", i, bf.Bit(i))
		}
	}
}