Skip to content

Commit 7ec13a2

Browse files
committed
Add BitArray.Toggle()
1 parent b1d5663 commit 7ec13a2

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

bitarray.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,18 @@ func (ba *BitArray) unset(idx int) {
112112
ba.data[n] &^= 1 << i
113113
}
114114

115+
// Toggle toggles the state of the bit at index idx and reports whether it is set after being toggled.
116+
func (ba *BitArray) Toggle(idx int) bool {
117+
ba.checkIdx(idx)
118+
b := ba.get(idx)
119+
if b {
120+
ba.unset(idx)
121+
} else {
122+
ba.set(idx)
123+
}
124+
return !b
125+
}
126+
115127
// Get reports whether the bit at index idx is set.
116128
func (ba *BitArray) Get(idx int) bool {
117129
ba.checkIdx(idx)

bitarray_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -185,6 +185,16 @@ func TestUnsetIdxSize(t *testing.T) {
185185
t.Error("did not panic")
186186
}
187187

188+
func TestToggle(t *testing.T) {
189+
want := "1000000010"
190+
ba := New(10, 9, 0)
191+
ba.Toggle(0)
192+
ba.Toggle(1)
193+
if got := ba.String(); got != want {
194+
t.Errorf("got %q, want %q", got, want)
195+
}
196+
}
197+
188198
func TestGet(t *testing.T) {
189199
s := "0100110101"
190200
tests := []struct {

0 commit comments

Comments
 (0)