github.com/machinefi/w3bstream@v1.6.5-rc9.0.20240426031326-b8c7c4876e72/pkg/depends/conf/id/id_gen_impl.go (about)

     1  package id
     2  
     3  import (
     4  	"github.com/machinefi/w3bstream/pkg/depends/base/types"
     5  	"github.com/machinefi/w3bstream/pkg/depends/base/types/snowflake_id"
     6  )
     7  
     8  func NewSFIDGenerator() (SFIDGenerator, error) {
     9  	return NewSFIDGeneratorWithWorkerID(snowflake_id.WorkerIDFromLocalIP())
    10  }
    11  
    12  func NewSFIDGeneratorWithWorkerID(wid uint32) (SFIDGenerator, error) {
    13  	sf, err := sff.NewSnowflake(wid)
    14  	if err != nil {
    15  		return nil, err
    16  	}
    17  	return &SFIDGeneratorImpl{sf}, nil
    18  }
    19  
    20  func MustNewSFIDGenerator() SFIDGenerator {
    21  	g, err := NewSFIDGenerator()
    22  	if err != nil {
    23  		panic(err)
    24  	}
    25  	return g
    26  }
    27  
    28  func MustNewSFIDGeneratorWithWorkerID(wid uint32) SFIDGenerator {
    29  	g, err := NewSFIDGeneratorWithWorkerID(wid)
    30  	if err != nil {
    31  		panic(err)
    32  	}
    33  	return g
    34  }
    35  
    36  type SFIDGeneratorImpl struct{ *snowflake_id.Snowflake }
    37  
    38  func (sfg *SFIDGeneratorImpl) MustGenSFID() types.SFID {
    39  	id, err := sfg.ID()
    40  	if err != nil {
    41  		panic(err)
    42  	}
    43  	return types.SFID(id)
    44  }
    45  
    46  func (sfg *SFIDGeneratorImpl) MustGenSFIDs(n int) types.SFIDs {
    47  	var ids = make(types.SFIDs, 0, n)
    48  	for i := 0; i < n; i++ {
    49  		id, err := sfg.ID()
    50  		if err != nil {
    51  			panic(err)
    52  		}
    53  		ids = append(ids, types.SFID(id))
    54  	}
    55  	return ids
    56  }