github.com/lirm/aeron-go@v0.0.0-20230415210743-920325491dc4/aeron/atomic/boolean.go (about)

     1  /*
     2  Copyright 2016 Stanislav Liberman
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8  http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package atomic
    18  
    19  import (
    20  	"sync/atomic"
    21  )
    22  
    23  const (
    24  	// True value for atomic.Bool
    25  	True int32 = 1
    26  	// False value for atomic.Bool
    27  	False int32 = 0
    28  )
    29  
    30  // Bool is an atomic boolean implementation used by aeron-go
    31  type Bool struct {
    32  	val int32
    33  }
    34  
    35  // Get returns the current state of the variable
    36  func (b *Bool) Get() bool {
    37  	return atomic.LoadInt32(&b.val) == True
    38  }
    39  
    40  // Set atomically sets the value of the variable
    41  func (b *Bool) Set(val bool) {
    42  	if val {
    43  		atomic.StoreInt32(&b.val, True)
    44  	} else {
    45  		atomic.StoreInt32(&b.val, False)
    46  	}
    47  }
    48  
    49  // CompareAndSet performs an atomic CAS operation on this variable
    50  func (b *Bool) CompareAndSet(oldVal, newVal bool) bool {
    51  	var old, newer int32
    52  	if oldVal {
    53  		old = True
    54  	} else {
    55  		old = False
    56  	}
    57  
    58  	if newVal {
    59  		newer = True
    60  	} else {
    61  		newer = False
    62  	}
    63  
    64  	return atomic.CompareAndSwapInt32(&b.val, old, newer)
    65  }