github.com/insolar/vanilla@v0.0.0-20201023172447-248fdf805322/atomickit/bool.go (about)

     1  // Copyright 2020 Insolar Network Ltd.
     2  // All rights reserved.
     3  // This material is licensed under the Insolar License version 1.0,
     4  // available at https://github.com/insolar/assured-ledger/blob/master/LICENSE.md.
     5  
     6  package atomickit
     7  
     8  import (
     9  	"strconv"
    10  	"sync/atomic"
    11  )
    12  
    13  func NewBool(initValue bool) Bool {
    14  	if initValue {
    15  		return Bool{1}
    16  	}
    17  	return Bool{}
    18  }
    19  
    20  type Bool struct {
    21  	v uint32
    22  }
    23  
    24  func (p *Bool) Load() bool {
    25  	return atomic.LoadUint32(&p.v) != 0
    26  }
    27  
    28  func (p *Bool) Store(v bool) {
    29  	if v {
    30  		atomic.StoreUint32(&p.v, 1)
    31  	} else {
    32  		atomic.StoreUint32(&p.v, 0)
    33  	}
    34  }
    35  
    36  func (p *Bool) Set() {
    37  	atomic.StoreUint32(&p.v, 1)
    38  }
    39  
    40  func (p *Bool) Unset() {
    41  	atomic.StoreUint32(&p.v, 0)
    42  }
    43  
    44  func (p *Bool) Swap(v bool) bool {
    45  	if v {
    46  		return atomic.SwapUint32(&p.v, 1) != 0
    47  	}
    48  	return atomic.SwapUint32(&p.v, 0) != 0
    49  }
    50  
    51  func (p *Bool) CompareAndFlip(old bool) bool {
    52  	if old {
    53  		return atomic.CompareAndSwapUint32(&p.v, 1, 0)
    54  	}
    55  	return atomic.CompareAndSwapUint32(&p.v, 0, 1)
    56  }
    57  
    58  func (p *Bool) Flip() bool {
    59  	for v := atomic.LoadUint32(&p.v);; {
    60  		if v != 0 {
    61  			if atomic.CompareAndSwapUint32(&p.v, v, 0) {
    62  				return false
    63  			}
    64  		} else {
    65  			if atomic.CompareAndSwapUint32(&p.v, 0, 1) {
    66  				return true
    67  			}
    68  		}
    69  	}
    70  }
    71  
    72  func (p *Bool) String() string {
    73  	return strconv.FormatBool(p.Load())
    74  }