From 9e538c6d38b9d98b1bd1092f2ced66a269f5ce32 Mon Sep 17 00:00:00 2001 From: barryz Date: Tue, 23 Jul 2019 23:43:19 +0800 Subject: [PATCH] implments Toggle method more explicit and simple. --- README.md | 2 +- bool.go | 6 +++--- bool_test.go | 13 +++++++++++-- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 627883d..810b1ae 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/bool.go b/bool.go index 401c11f..3a3ca64 100644 --- a/bool.go +++ b/bool.go @@ -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 diff --git a/bool_test.go b/bool_test.go index 2e9b4f0..18760b0 100644 --- a/bool_test.go +++ b/bool_test.go @@ -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) {