snowflake

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2024 License: MIT Imports: 5 Imported by: 0

README

go-snowflake

GoDoc Go Report Card codecov


About it

A simple Twitter snowflake sequence generator.

Futures
  • The lifecycle of the generator is 69 years.
  • It can be leveraged on distributed systems.
  • It can ensure the correct sequence order is on the one node strongly, but the correct sequence order is on the distributed systems weakly because of NTP.
Format
+--------------------------------------------------------------------------+
| 1 Bit Unused | 41 Bit Timestamp |  8 Bit NodeID  |   14 Bit Sequence ID  |
+--------------------------------------------------------------------------+
Example
package main

import (
        "fmt"
        "time"

        "github.com/0x726f6f6b6965/go-snowflake"
)

func main() {
    var (
        startTime = time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
        nodeID int64 = 3
    )
	// Create a new generator 
	generator, err := snowflake.NewGenerator(nodeID, startTime)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Generate a sequence.
	sequence, _ := generator.Next()

	// Print out the sequence.
	fmt.Printf("Uint64 Sequence: %d\n", sequence.Uint64())
	fmt.Printf("String Sequence: %s\n", sequence.String())
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (

	// ErrInvalidNode - invalid node id
	ErrInvalidNode = fmt.Errorf("invalid node id; must be 0 ≤ id < %d", maxNode)

	// ErrStartZero - the error of starting time is zero
	ErrStartZero = errors.New("the start time cannot be a zero value")

	// ErrStartFuture - the error of starting time is in the future
	ErrStartFuture = errors.New("the start time cannot be greater than the current millisecond")

	// ErrStartExceed - the start time is more than 69 years ago.
	ErrStartExceed = errors.New("the maximum life cycle of the snowflake algorithm is 69 years")

	// ErrGeneratorClosed
	ErrGeneratorClosed = errors.New("generator is closed")
)

Functions

This section is empty.

Types

type Generator

type Generator interface {
	// Next - get an unused sequence
	Next() (*big.Int, error)
	// Close - close the generator
	Close()
}

func NewGenerator

func NewGenerator(node int64, start time.Time) (Generator, error)

Jump to

Keyboard shortcuts

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