flake

package module
v0.0.0-...-c680a61 Latest Latest
Warning

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

Go to latest
Published: Jun 4, 2018 License: Apache-2.0 Imports: 6 Imported by: 3

README

go-flake

go-flake generates unique identifiers that are roughly sortable by time.

Flake can run on a cluster of machines and still generate unique IDs without requiring worker coordination.

A Flake ID is a 64-bit integer will the following components:

  • 41 bits is the timestamp with millisecond precision
  • 10 bits is the host id (uses IP modulo 2^10)
  • 13 bits is an auto-incrementing sequence for ID requests within the same millisecond

Installation

go get github.com/davidnarayan/go-flake

Example

package main

import (
	"log"
	"github.com/davidnarayan/go-flake"
)

func main() {
	f, err := flake.New()

	if err != nil {
		log.Fatal(err)
	}

	id := f.NextId()
	fmt.Println(id)
	fmt.Println(id.String())
}

Credit

This work is based on code and concepts from the following:

Documentation

Index

Constants

View Source
const (
	HostBits     = 10
	SequenceBits = 13
)

Variables

View Source
var (
	// Custom Epoch so the timestamp can fit into 41 bits.
	// Jan 1, 2014 00:00:00 UTC
	Epoch       time.Time = time.Date(2014, 1, 1, 0, 0, 0, 0, time.UTC)
	MaxHostId   uint64    = (1 << HostBits) - 1
	MaxSequence uint64    = (1 << SequenceBits) - 1
)

Functions

This section is empty.

Types

type Flake

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

Flake is a unique Id generator

func New

func New() (*Flake, error)

New returns a new Id generator and a possible error condition

func (*Flake) NextId

func (f *Flake) NextId() Id

NextId returns a new Id from the generator

type Id

type Id uint64

Id represents a unique k-ordered Id

func (*Id) String

func (id *Id) String() string

String formats the Id as a 16 character hexadecimal string

func (*Id) Uint64

func (id *Id) Uint64() uint64

Uint64 formats the Id as an unsigned integer

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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