github.com/haraldrudell/parl@v0.4.176/unique-id-int.go (about)

     1  /*
     2  © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package parl
     7  
     8  import (
     9  	"strconv"
    10  	"sync/atomic"
    11  	"unsafe"
    12  
    13  	"github.com/haraldrudell/parl/perrors"
    14  )
    15  
    16  // UniqueIDUint64 generates executable-invocation-unique uint64 numbers 1…
    17  // Different series of uint64 from different generators does not have identity,
    18  // ie. they cannot be told apart.
    19  // Consider UniqueIDTypedUint64 to have identity.
    20  //
    21  // Usage:
    22  //
    23  //	var generator parl.UniqueIDUint64
    24  //	id := generator.ID()
    25  type UniqueIDint int
    26  
    27  var intSize = int(unsafe.Sizeof(2))
    28  
    29  // ID generates a unique uint64 1…. thread-safe
    30  func (u *UniqueIDint) ID() (uniqueID int) {
    31  	switch intSize {
    32  	case 4:
    33  		return int(atomic.AddInt32((*int32)(unsafe.Pointer(u)), 1))
    34  	case 8:
    35  		return int(atomic.AddInt64((*int64)(unsafe.Pointer(u)), 1))
    36  	}
    37  	panic(perrors.ErrorfPF("int size not 4 or 8: %d", intSize))
    38  }
    39  
    40  func (u *UniqueIDint) String() (s string) {
    41  	return "IDint:" + strconv.FormatInt(int64(*u), 10)
    42  }