fastid

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 29, 2023 License: MIT Imports: 3 Imported by: 1

README

fastid

build-img pkg-img reportcard-img coverage-img

Fast ID generator based on timestamp, sequence number and worker id.

Rationale

Generating IDs quickly is a common task. Making this quickly is a nice thing to have.

Features

  • Simple.
  • Thread-safe.
  • Time based.
  • Dependency-free.

Install

go get github.com/cristalhq/fastid

Example

gen, err := NewGenerator(100, 200)

id := gen.Next()

ts, seq, w := id.Parts()

ts = id.Timestamp()
seq = id.Sequence()
w = id.WorkerID()

Documentation

See these docs.

License

MIT License.

Documentation

Index

Constants

View Source
const (
	// DefaultEpoch is an epoch for a default generator.
	DefaultEpoch = 1500000000000

	// WorkerIDBits is how many bits are used for worked ID.
	WorkerIDBits = uint(10)
	// SequenceBits is how many bits are used for sequence number.
	SequenceBits = uint(12)

	// MaxWorkerID is a max possible worked ID.
	MaxWorkerID = (1 << WorkerIDBits) - 1
	// MaxSequenceID is a max possible sequence number.
	MaxSequenceID = (1 << SequenceBits) - 1
)

Variables

This section is empty.

Functions

func LastTimestamp

func LastTimestamp() int64

LastTimestamp returns a last generated timestamp.

Types

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

Generator represents IDs with a given epoch and workedID.

func NewGenerator

func NewGenerator(epoch int64, workerID int) (*Generator, error)

NewGenerator creates a new generator for IDs with a given epoch and workerID.

func (*Generator) LastID

func (g *Generator) LastID() ID

LastID returns a last generated ID.

func (*Generator) LastSequence

func (g *Generator) LastSequence() int

LastSequence returns a last generated sequence.

func (*Generator) LastTimestamp

func (g *Generator) LastTimestamp() int64

LastTimestamp returns a last generated timestamp.

func (*Generator) Next

func (g *Generator) Next() ID

Next returns a next ID.

type ID

type ID uint64

ID represents an ID value.

func LastID

func LastID() ID

LastID returns a last generated ID.

func Next

func Next() ID

Next returns a next ID.

func (ID) Parts

func (id ID) Parts() (int64, int, int)

Parts returns ID's parts(timestamp, sequence number, worker id).

func (ID) Sequence

func (id ID) Sequence() int

Sequence returns ID's sequence number.

func (ID) Timestamp

func (id ID) Timestamp() int64

Timestamp returns ID's timestamp (unix ms).

func (ID) WorkerID

func (id ID) WorkerID() int

WorkerID returns ID's worker id.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL