nxid

package module
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Aug 20, 2024 License: MIT Imports: 12 Imported by: 0

README

NXID: Generate XID by nanosecond

godoc license

Package nxid is a nanosecond-level globally unique ID generator library, derived from XID. NXID is specifically designed for scenarios requiring high-resolution timestamp precision.

Key Changes from Original XID

  • Utilizes an 8-byte nanosecond-level timestamp instead of a 4-byte second-level timestamp.
  • Better suited for time-sensitive ID generation, ensuring higher resolution timing.

Structure

  • 8-byte value representing the nanoseconds since the Unix epoch,
  • 3-byte machine identifier,
  • 2-byte process ID, and
  • 3-byte counter, starting with a random value.

The binary representation of the ID remains compatible with MongoDB's 12-byte Object IDs, but the time precision is significantly higher.

Advantages

  • Higher time resolution, making it suitable for applications where timestamp precision is essential.
  • Compact and URL-safe string representation (20 chars).

Comparison

Name Binary Size String Size Features
UUID 16 bytes 36 chars configuration-free, not sortable
shortuuid 16 bytes 22 chars configuration-free, not sortable
Snowflake 8 bytes up to 20 chars requires machine/DC configuration, central server, sortable
MongoID 12 bytes 24 chars configuration-free, sortable
xid 12 bytes 20 chars configuration-free, sortable, second-level precision
nxid 16 bytes 26 chars configuration-free, sortable, nanosecond-level precision

Features

  • Base32 hex encoded (20 chars when transported as a printable string, still sortable)
  • Configuration-free, no need for unique machine or data center IDs
  • K-ordered
  • Embedded time with nanosecond precision
  • Uniqueness guaranteed for 16,777,216 (24 bits) unique IDs per nanosecond and per host/process
  • Lock-free generation

Installation

go get github.com/ClayCheung/nxid

Usage

Generate a new NXID:

guid := nxid.New()

println(guid.String())
// Output example: 2vmide3burdh0kb22i1m0pln98

Retrieve embedded info:

guid.Machine()
guid.Pid()
guid.Time()
guid.Counter()

Benchmark

run benchmark in id_benchmark_test.go

# go test -bench=. -benchmem -cpu=1,2,4
BenchmarkNXID           22169484                52.01 ns/op            0 B/op          0 allocs/op
BenchmarkNXID-2         26748993                43.79 ns/op            0 B/op          0 allocs/op
BenchmarkNXID-4         31624129                42.95 ns/op            0 B/op          0 allocs/op
BenchmarkXID            24247342                49.69 ns/op            0 B/op          0 allocs/op
BenchmarkXID-2          27107719                42.16 ns/op            0 B/op          0 allocs/op
BenchmarkXID-4          35370450                46.31 ns/op            0 B/op          0 allocs/op
BenchmarkGoUUIDv1       12962964                92.62 ns/op           48 B/op          1 allocs/op
BenchmarkGoUUIDv1-2     10513396               113.9 ns/op            48 B/op          1 allocs/op
BenchmarkGoUUIDv1-4      7847894               152.9 ns/op            48 B/op          1 allocs/op
BenchmarkUUIDv4         11317635               106.7 ns/op            64 B/op          2 allocs/op
BenchmarkUUIDv4-2        9622802               124.1 ns/op            64 B/op          2 allocs/op
BenchmarkUUIDv4-4        8338959               143.7 ns/op            64 B/op          2 allocs/op
BenchmarkUUIDv6         12215884                96.62 ns/op           48 B/op          1 allocs/op
BenchmarkUUIDv6-2        9493748               125.4 ns/op            48 B/op          1 allocs/op
BenchmarkUUIDv6-4        7318026               167.4 ns/op            48 B/op          1 allocs/op
BenchmarkUUIDv7          7409154               161.3 ns/op            64 B/op          2 allocs/op
BenchmarkUUIDv7-2        6529828               183.6 ns/op            64 B/op          2 allocs/op
BenchmarkUUIDv7-4        6162991               194.6 ns/op            64 B/op          2 allocs/op

Licensing

All source code is licensed under the MIT License.


References

Documentation

Overview

package nxid is a globally unique id generator suited for web scale

Xid is using Mongo Object ID algorithm to generate globally unique ids: https://docs.mongodb.org/manual/reference/object-id/

  • 4-byte value representing the seconds since the Unix epoch,
  • 3-byte machine identifier,
  • 2-byte process id, and
  • 3-byte counter, starting with a random value.

The binary representation of the id is compatible with Mongo 12 bytes Object IDs. The string representation is using base32 hex (w/o padding) for better space efficiency when stored in that form (20 bytes). The hex variant of base32 is used to retain the sortable property of the id.

Xid doesn't use base64 because case sensitivity and the 2 non alphanum chars may be an issue when transported as a string between various systems. Base36 wasn't retained either because 1/ it's not standard 2/ the resulting size is not predictable (not bit aligned) and 3/ it would not remain sortable. To validate a base32 `xid`, expect a 20 chars long, all lowercase sequence of `a` to `v` letters and `0` to `9` numbers (`[0-9a-v]{20}`).

UUID is 16 bytes (128 bits), snowflake is 8 bytes (64 bits), xid stands in between with 12 bytes with a more compact string representation ready for the web and no required configuration or central generation server.

Features:

  • Size: 12 bytes (96 bits), smaller than UUID, larger than snowflake
  • Base32 hex encoded by default (16 bytes storage when transported as printable string)
  • Non configured, you don't need set a unique machine and/or data center id
  • K-ordered
  • Embedded time with 1 second precision
  • Unicity guaranteed for 16,777,216 (24 bits) unique ids per second and per host/process

Best used with xlog's RequestIDHandler (https://godoc.org/github.com/rs/xlog#RequestIDHandler).

References:

Index

Constants

View Source
const (
	// ErrInvalidID is returned when trying to unmarshal an invalid ID.
	ErrInvalidID strErr = "xid: invalid ID"
)

Variables

This section is empty.

Functions

func Sort

func Sort(ids []ID)

Sort sorts an array of IDs inplace. It works by wrapping `[]ID` and use `sort.Sort`.

Types

type ID

type ID [rawLen]byte

ID represents a unique request id

func FromBytes

func FromBytes(b []byte) (ID, error)

FromBytes convert the byte array representation of `ID` back to `ID`

func FromString

func FromString(id string) (ID, error)

FromString reads an ID from its string representation

func New

func New() ID

New generates a globally unique ID

func NewWithTime

func NewWithTime(t time.Time) ID

NewWithTime generates a globally unique ID with the passed in time

func NilID

func NilID() ID

NilID returns a zero value for `xid.ID`.

func (ID) Bytes

func (id ID) Bytes() []byte

Bytes returns the byte array representation of `ID`

func (ID) Compare

func (id ID) Compare(other ID) int

Compare returns an integer comparing two IDs. It behaves just like `bytes.Compare`. The result will be 0 if two IDs are identical, -1 if current id is less than the other one, and 1 if current id is greater than the other.

func (ID) Counter

func (id ID) Counter() int32

Counter returns the incrementing value part of the id. It's a runtime error to call this method with an invalid id.

func (ID) Encode

func (id ID) Encode(dst []byte) []byte

Encode encodes the id using base32 encoding, writing 26 bytes to dst and return it.

func (ID) IsNil

func (id ID) IsNil() bool

IsNil Returns true if this is a "nil" ID

func (ID) IsZero

func (id ID) IsZero() bool

Alias of IsNil

func (ID) Machine

func (id ID) Machine() []byte

Machine returns the 3-byte machine id part of the id. It's a runtime error to call this method with an invalid id.

func (ID) MarshalJSON

func (id ID) MarshalJSON() ([]byte, error)

MarshalJSON implements encoding/json Marshaler interface

func (ID) MarshalText

func (id ID) MarshalText() ([]byte, error)

MarshalText implements encoding/text TextMarshaler interface

func (ID) Pid

func (id ID) Pid() uint16

Pid returns the process id part of the id. It's a runtime error to call this method with an invalid id.

func (*ID) Scan

func (id *ID) Scan(value interface{}) (err error)

Scan implements the sql.Scanner interface.

func (ID) String

func (id ID) String() string

String returns a base32 hex lowercased with no padding representation of the id (char set is 0-9, a-v).

func (ID) Time

func (id ID) Time() time.Time

Time returns the timestamp part of the id. It's a runtime error to call this method with an invalid id.

func (*ID) UnmarshalJSON

func (id *ID) UnmarshalJSON(b []byte) error

UnmarshalJSON implements encoding/json Unmarshaler interface

func (*ID) UnmarshalText

func (id *ID) UnmarshalText(text []byte) error

UnmarshalText implements encoding/text TextUnmarshaler interface

func (ID) Value

func (id ID) Value() (driver.Value, error)

Value implements the driver.Valuer interface.

Directories

Path Synopsis
b

Jump to

Keyboard shortcuts

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