github.com/git-amp/amp-sdk-go@v0.7.5/stdlib/symbol/issuer.go (about)

     1  package symbol
     2  
     3  import (
     4  	"sync/atomic"
     5  )
     6  
     7  func NewVolatileIssuer(startAt ID) Issuer {
     8  	iss := &atomicIssuer{}
     9  	iss.nextID.Store(uint32(startAt))
    10  	iss.refCount.Store(1)
    11  	return iss
    12  }
    13  
    14  // atomicIssuer implements symbol.Issuer using an atomic int
    15  type atomicIssuer struct {
    16  	refCount atomic.Int32
    17  	nextID   atomic.Uint32
    18  }
    19  
    20  func (iss *atomicIssuer) IssueNextID() (ID, error) {
    21  	if iss.refCount.Load() <= 0 {
    22  		return 0, ErrIssuerNotOpen
    23  	}
    24  	nextID := iss.nextID.Add(1)
    25  	return ID(nextID), nil
    26  }
    27  
    28  func (iss *atomicIssuer) AddRef() {
    29  	if iss.refCount.Add(1) <= 1 {
    30  		panic("AddRef() called on closed issuer")
    31  	}
    32  }
    33  
    34  func (iss *atomicIssuer) Close() error {
    35  	newRefCount := iss.refCount.Add(-1)
    36  	if newRefCount < 0 {
    37  		return ErrIssuerNotOpen
    38  	}
    39  	return nil
    40  }