go.charczuk.com@v0.0.0-20240327042549-bc490516bd1a/sdk/async/latch_thin.go (about)

     1  /*
     2  
     3  Copyright (c) 2023 - Present. Will Charczuk. All rights reserved.
     4  Use of this source code is governed by a MIT license that can be found in the LICENSE file at the root of the repository.
     5  
     6  */
     7  
     8  package async
     9  
    10  import "sync/atomic"
    11  
    12  // LatchThin is an implementation of a subset of the latch api
    13  // that does not support notifying on channels.
    14  //
    15  // As a result, it's much easier to embed and use as a zero value.
    16  type LatchThin struct {
    17  	state int32
    18  }
    19  
    20  // Reset resets the latch.
    21  func (lt *LatchThin) Reset() {
    22  	atomic.StoreInt32(&lt.state, LatchStopped)
    23  }
    24  
    25  // CanStart returns if the latch can start.
    26  func (lt LatchThin) CanStart() bool {
    27  	return atomic.LoadInt32(&lt.state) == LatchStopped
    28  }
    29  
    30  // CanStop returns if the latch can stop.
    31  func (lt LatchThin) CanStop() bool {
    32  	return atomic.LoadInt32(&lt.state) == LatchStarted
    33  }
    34  
    35  // IsStarting returns if the latch state is LatchStarting
    36  func (lt LatchThin) IsStarting() bool {
    37  	return atomic.LoadInt32(&lt.state) == LatchStarting
    38  }
    39  
    40  // IsStarted returns if the latch state is LatchStarted.
    41  func (lt LatchThin) IsStarted() bool {
    42  	return atomic.LoadInt32(&lt.state) == LatchStarted
    43  }
    44  
    45  // IsStopping returns if the latch state is LatchStopping.
    46  func (lt LatchThin) IsStopping() bool {
    47  	return atomic.LoadInt32(&lt.state) == LatchStopping
    48  }
    49  
    50  // IsStopped returns if the latch state is LatchStopped.
    51  func (lt LatchThin) IsStopped() bool {
    52  	return atomic.LoadInt32(&lt.state) == LatchStopped
    53  }
    54  
    55  // Starting signals the latch is starting.
    56  func (lt *LatchThin) Starting() bool {
    57  	return atomic.CompareAndSwapInt32(&lt.state, LatchStopped, LatchStarting)
    58  }
    59  
    60  // Started signals that the latch is started and has entered the `IsStarted` state.
    61  func (lt *LatchThin) Started() bool {
    62  	return atomic.CompareAndSwapInt32(&lt.state, LatchStarting, LatchStarted)
    63  }
    64  
    65  // Stopping signals the latch to stop.
    66  func (lt *LatchThin) Stopping() bool {
    67  	return atomic.CompareAndSwapInt32(&lt.state, LatchStarted, LatchStopping)
    68  }
    69  
    70  // Stopped signals the latch has stopped.
    71  func (lt *LatchThin) Stopped() bool {
    72  	return atomic.CompareAndSwapInt32(&lt.state, LatchStopping, LatchStopped)
    73  }