Skip to content

Commit

Permalink
implments Toggle method more explicit and simple.
Browse files Browse the repository at this point in the history
  • Loading branch information
barryz committed Jul 23, 2019
1 parent 774dbea commit 9e538c6
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ cond.IsSet() // Returns true
cond.UnSet() // Set to false
cond.SetTo(true) // Set to whatever you want
cond.SetToIf(false, true) // Set to true if it is false, returns false(not set)
cond.Toggle() bool // Toggle the boolean value atomically and returns the previous value.
cond.Toggle() *AtomicBool // Negates boolean atomically and returns a new AtomicBool object which holds previous boolean value.


// embedding
Expand Down
6 changes: 3 additions & 3 deletions bool.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,9 @@ func (ab *AtomicBool) SetTo(yes bool) {
}
}

// Toggle negates boolean atomically and returns the previous value.
func (ab *AtomicBool) Toggle() bool {
return (atomic.AddInt32((*int32)(ab), 1)-1)&1 == 1
// Toggle negates boolean atomically and returns a new AtomicBool object which holds previous boolean value.
func (ab *AtomicBool) Toggle() *AtomicBool {
return NewBool(atomic.AddInt32((*int32)(ab), 1)&1 == 0)
}

// SetToIf sets the Boolean to new only if the Boolean matches the old
Expand Down
13 changes: 11 additions & 2 deletions bool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,11 +50,20 @@ func TestBool(t *testing.T) {
t.Fatal("AtomicBool.SetTo(false, true) failed")
}

_ = v.Toggle() // expected false
v = New()
if v.IsSet() {
t.Fatal("AtomicBool.Toggle() failed")
t.Fatal("Empty value of AtomicBool should be false")
}

_ = v.Toggle()
if !v.IsSet() {
t.Fatal("AtomicBool.Toggle() to true failed")
}

prev := v.Toggle()
if v.IsSet() == prev.IsSet() {
t.Fatal("AtomicBool.Toggle() to false failed")
}
}

func TestRace(t *testing.T) {
Expand Down

0 comments on commit 9e538c6

Please sign in to comment.