Skip to content

Commit

Permalink
Clean up tests / add examples.
Browse files Browse the repository at this point in the history
  • Loading branch information
Jake Kaufman committed Oct 16, 2015
1 parent 65c4b72 commit 6110063
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 9 deletions.
9 changes: 2 additions & 7 deletions concurrent/atomicbool/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,6 @@ b.Set(true)

// get current value
b.Get()

// compare b to old and set b to new if they match
// swapped is true iff b was set to the second arg
swapped := b.CompareandSwap(old, new)

// swap values
old := b.Swap(false)
```

See the docs for examples of more complex usage.
4 changes: 4 additions & 0 deletions concurrent/atomicbool/atomicbool.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,13 @@ import (
)

type AtomicBool struct {
// value is either be 1 or 0
// 1 == true
// 0 == false
value *int32
}

// Creates a new AtomicBool with a default value of false
func New() *AtomicBool {
ab := new(AtomicBool)
ab.value = new(int32)
Expand Down
38 changes: 36 additions & 2 deletions concurrent/atomicbool/atomicbool_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package atomicbool

import (
"fmt"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -16,20 +17,53 @@ func TestiToB(t *testing.T) {
assert.Equal(t, iToB(0), false)
}

func ExampleAtomicBool_Swap() {
// default is false just like bool
b := New()

// set to true
b.Set(true)

// swap values
fmt.Println(b.Swap(false))
// Output:
// true
}
func ExampleAtomicBool_CompareAndSwap() {
b := New()

// set to true
b.Set(true)

// get current value
fmt.Println(b.Get())

// compare b to old and set b to new if they match
// swapped is true iff b was set to the second arg
fmt.Println(b.CompareAndSwap(true, false))

// CompareAndSwap does nothing here as b's value is false
fmt.Println(b.CompareAndSwap(true, false))
// Output:
// true
// true
// false
}

func TestGet(t *testing.T) {
b := New()
assert.Equal(t, b.Get(), false)
}

func TestSetGet(t *testing.T) {
func TestSet(t *testing.T) {
b := New()
b.Set(true)
assert.Equal(t, b.Get(), true)
b.Set(false)
assert.Equal(t, b.Get(), false)
}

func TestCAS(t *testing.T) {
func TestCompareAndSwap(t *testing.T) {
b := New()
var ret bool
ret = b.CompareAndSwap(true, false)
Expand Down

0 comments on commit 6110063

Please sign in to comment.