github.com/zhongdalu/gf@v1.0.0/g/container/gtype/bool.go (about)

     1  // Copyright 2018 gf Author(https://github.com/zhongdalu/gf). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/zhongdalu/gf.
     6  
     7  package gtype
     8  
     9  import (
    10  	"sync/atomic"
    11  )
    12  
    13  type Bool struct {
    14  	value int32
    15  }
    16  
    17  // NewBool returns a concurrent-safe object for bool type,
    18  // with given initial value <value>.
    19  func NewBool(value ...bool) *Bool {
    20  	t := &Bool{}
    21  	if len(value) > 0 {
    22  		if value[0] {
    23  			t.value = 1
    24  		} else {
    25  			t.value = 0
    26  		}
    27  	}
    28  	return t
    29  }
    30  
    31  // Clone clones and returns a new concurrent-safe object for bool type.
    32  func (v *Bool) Clone() *Bool {
    33  	return NewBool(v.Val())
    34  }
    35  
    36  // Set atomically stores <value> into t.value and returns the previous value of t.value.
    37  func (v *Bool) Set(value bool) (old bool) {
    38  	if value {
    39  		old = atomic.SwapInt32(&v.value, 1) == 1
    40  	} else {
    41  		old = atomic.SwapInt32(&v.value, 0) == 1
    42  	}
    43  	return
    44  }
    45  
    46  // Val atomically loads t.valueue.
    47  func (v *Bool) Val() bool {
    48  	return atomic.LoadInt32(&v.value) > 0
    49  }
    50  
    51  // Cas executes the compare-and-swap operation for value.
    52  func (v *Bool) Cas(old, new bool) bool {
    53  	var oldInt32, newInt32 int32
    54  	if old {
    55  		oldInt32 = 1
    56  	}
    57  	if new {
    58  		newInt32 = 1
    59  	}
    60  	return atomic.CompareAndSwapInt32(&v.value, oldInt32, newInt32)
    61  }