flake

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Dec 1, 2020 License: MIT Imports: 4 Imported by: 0

README

go-flake

This is a simple go implementation of the twitter snowflake id generator.

The id breakdown is:

  • 48 bits of a epoch time in milliseconds
  • 5 bits of a worker id
  • 12 bits of sequence

There are two ways to use the generator

  • straight call to generate the id
    • this method will allow the user to pass the worker and seqeunce
  • use the generator struct
    • this is for one worker id and will handle auto update of the sequence and check for rollover
    • Errors can help with identifying possible id collision

Examples

The following are the two implementation examples.

Function Generation

import (
	"fmt"

	"github.com/g8rswimmer/go-flake"
)

const (
	worker = uint64(10)
	seq    = uint64(1000)
)

func main() {
	id, err := flake.Generate(worker, seq)
	if err != nil {
		panic(err)
	}
	fmt.Printf("The generated id %v\n", id)
}
Generator
package main

import (
	"fmt"

	"github.com/g8rswimmer/go-flake"
)

const (
	worker = uint64(10)
)

func main() {
	gen, err := flake.New(worker)
	if err != nil {
		panic(err)
	}

	for i := 0; i < 10; i++ {
		id, err := gen.Generate()
		if err != nil {
			panic(err)
		}
		fmt.Printf("The generated id %v\n", id)
	}
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrSequenceRollover = errors.New("flake generator sequence rollover")

ErrSequenceRollover is an error when the sequence number rolls over and the epoch time has not incremented

Functions

This section is empty.

Types

type Generator

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

Generator will create a new id from the worker

func New

func New(worker uint64) (*Generator, error)

New will create a new generator for the worker

func (*Generator) Generate

func (g *Generator) Generate() (ID, error)

Generate will create a new id

func (*Generator) Wait

func (g *Generator) Wait()

Wait will sleep for a millisecond, if there was an error on generate, this will help make sure that the sequence rollover will be handled.

type ID

type ID uint64

ID is the flake id 46 bits of time, 6 bits of worker and 12 bits of sequence

const (
	// InvalidID is an invalid id
	InvalidID ID = 0
)

func Generate

func Generate(worker, seq uint64) (ID, error)

Generate will create an id from the worker and sequence requested

func (ID) Decimal

func (i ID) Decimal() string

Decimal is the ID decimal string

func (ID) String

func (i ID) String() string

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

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