github.com/haraldrudell/parl@v0.4.176/unique-id-typed-uint64.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  )
    12  
    13  // UniqueIDTypedUint64 generates integer-based opaque uniquely-typed IDs. Thread-safe.
    14  //   - Different named-type series have their own unique type and can be told apart.
    15  //   - The named types are ordered integer-based with String method implementing fmt.Stringer.
    16  //
    17  // Usage:
    18  //
    19  //	type T uint64
    20  //	var generator parl.UniqueIDTypedUint64[T]
    21  //	func (t T) String() string { return generator.StringT(t) }
    22  //	someID := generator.ID()
    23  type UniqueIDTypedUint64[T ~uint64] uint64
    24  
    25  // ID generates a unique ID of integral type. Thread-safe
    26  func (u *UniqueIDTypedUint64[T]) ID() (uniqueT T) {
    27  	return T(atomic.AddUint64((*uint64)(u), 1))
    28  }
    29  
    30  // "parl.T:2", zero-value t prints "parl.T:0"
    31  func (u *UniqueIDTypedUint64[T]) StringT(t T) (s string) {
    32  	return Sprintf("%T:%s", t, strconv.FormatUint(uint64(t), 10))
    33  }