guuid

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

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

Go to latest
Published: Dec 2, 2025 License: MIT Imports: 11 Imported by: 0

README

GUUID

GUUID is a lightweight and efficient library for generating Universally Unique Identifiers (UUIDs) in Go. It provides fast, standards-compliant UUID generation suitable for distributed systems, databases, and any application requiring unique identifiers. GUUID supports multiple UUID versions and is designed for simplicity, performance, and ease of integration.

Features

  • UUIDv7 Support: Generate time-ordered UUIDs with millisecond precision timestamps, perfect for database primary keys and distributed systems requiring sortable identifiers
  • High Performance: Optimized for speed with minimal memory allocations
  • Standards Compliant: Follows RFC 4122 and draft RFC for UUIDv7 specifications
  • Thread Safe: Concurrent generation without performance penalties
  • Zero Dependencies: Pure Go implementation with no external dependencies

UUIDv7 Overview

UUIDv7 is the latest UUID version that combines the benefits of time-based ordering with cryptographic randomness. Unlike traditional UUIDs, UUIDv7 generates identifiers that are naturally sortable by creation time, making them ideal for:

  • Database primary keys (improved B-tree performance)
  • Distributed systems requiring time-ordered identifiers
  • Event sourcing and audit logs
  • Any scenario where chronological ordering matters

Each UUIDv7 contains:

  • 48-bit timestamp (millisecond precision)
  • 12-bit random data for sub-millisecond ordering
  • 62-bit random data for uniqueness
  • Version and variant bits as per RFC specification

Comparison: Snowflake Algorithm vs UUIDv7

Feature Snowflake Algorithm UUIDv7
Total Size 64-bit (8 bytes) 128-bit (16 bytes)
Data Type bigint (long integer) UUID / binary(16)
ID Structure 1-bit sign + 41-bit timestamp + 10-bit node ID + 12-bit sequence 48-bit timestamp + 6-bit version/variant + 74-bit random data
Conflict Avoidance Assign unique node ID (Worker ID) Probabilistic (relies on 74-bit random data)
Sortability Yes (chronologically increasing) Yes (chronologically increasing)
Generation Limits Hard limit: 4096 per node per millisecond (12-bit sequence) No hard limit: probabilistic, can generate astronomical numbers in same millisecond
Operational Cost High Zero

https://www.rfc-editor.org/rfc/rfc9562.html

Documentation

Overview

Package guuid provides a lightweight and efficient implementation of Universally Unique Identifiers (UUIDs) in Go, with primary support for UUIDv7.

UUIDv7 is a time-ordered UUID that combines the benefits of time-based ordering with cryptographic randomness. Unlike traditional UUIDs, UUIDv7 generates identifiers that are naturally sortable by creation time, making them ideal for:

  • Database primary keys (improved B-tree performance)
  • Distributed systems requiring time-ordered identifiers
  • Event sourcing and audit logs
  • Any scenario where chronological ordering matters

Basic Usage:

// Generate a new UUIDv7
id, err := guuid.New()
if err != nil {
    log.Fatal(err)
}
fmt.Println(id.String())

// Parse a UUID from string
id, err := guuid.Parse("f47ac10b-58cc-4372-a567-0e02b2c3d479")
if err != nil {
    log.Fatal(err)
}

// Get timestamp from UUIDv7
timestamp := id.Timestamp()
time := id.Time()

Custom Generator:

// Create a custom generator for better performance in tight loops
gen := guuid.NewGenerator()
for i := 0; i < 1000; i++ {
    id, err := gen.New()
    if err != nil {
        log.Fatal(err)
    }
    // Use id...
}

Thread Safety:

All operations are thread-safe. The default generator can be used concurrently from multiple goroutines without additional synchronization.

Standards Compliance:

This implementation follows RFC 4122 and RFC 9562 specifications for UUIDs. The UUIDv7 format includes:

  • 48-bit timestamp (millisecond precision)
  • 12-bit random data for sub-millisecond ordering
  • 62-bit random data for uniqueness
  • Version and variant bits as per RFC specification

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidFormat indicates that the UUID string format is invalid
	ErrInvalidFormat = errors.New("guuid: invalid UUID format")

	// ErrInvalidLength indicates that the UUID byte slice has incorrect length
	ErrInvalidLength = errors.New("guuid: invalid UUID length (expected 16 bytes)")

	// ErrInvalidVersion indicates that the UUID version is not supported
	ErrInvalidVersion = errors.New("guuid: invalid or unsupported UUID version")

	// ErrInvalidVariant indicates that the UUID variant is not RFC 4122
	ErrInvalidVariant = errors.New("guuid: invalid UUID variant (expected RFC 4122)")
)

Functions

This section is empty.

Types

type Generator

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

Generator is a thread-safe UUIDv7 generator that ensures monotonicity within the same millisecond by using a counter with random data.

func NewGenerator

func NewGenerator() *Generator

NewGenerator creates a new UUIDv7 generator with crypto/rand as the random source

func NewGeneratorWithReader

func NewGeneratorWithReader(r io.Reader) *Generator

NewGeneratorWithReader creates a new UUIDv7 generator with a custom random source. This is primarily useful for testing with deterministic random sources.

func (*Generator) New

func (g *Generator) New() (UUID, error)

New generates a new UUIDv7 with the current timestamp. This method is thread-safe and ensures monotonic ordering of UUIDs generated within the same millisecond.

func (*Generator) NewWithTime

func (g *Generator) NewWithTime(t time.Time) (UUID, error)

NewWithTime generates a new UUIDv7 with the specified timestamp. This method is thread-safe and ensures monotonic ordering.

type UUID

type UUID [16]byte

UUID represents a Universally Unique Identifier as defined by RFC 4122 and RFC 9562. The UUID is a 128-bit (16 byte) value that is used to uniquely identify information.

var Nil UUID

Nil is the nil UUID (all zeros)

func DecodeFromBase64

func DecodeFromBase64(s string) (UUID, error)

DecodeFromBase64 decodes a base64 string to UUID (URL-safe encoding)

func DecodeFromBase64Std

func DecodeFromBase64Std(s string) (UUID, error)

DecodeFromBase64Std decodes a standard base64 string to UUID

func DecodeFromHex

func DecodeFromHex(s string) (UUID, error)

DecodeFromHex decodes a hexadecimal string to UUID

func FromBytes

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

FromBytes creates a UUID from a byte slice

func Must

func Must(uuid UUID, err error) UUID

Must is a helper that wraps a call to a function returning (UUID, error) and panics if the error is non-nil. It is intended for use in variable initializations such as:

var id = guuid.Must(generator.New())

func MustFromBytes

func MustFromBytes(b []byte) UUID

MustFromBytes is like FromBytes but panics on error

func MustParse

func MustParse(s string) UUID

MustParse is like Parse but panics if the string cannot be parsed. It simplifies safe initialization of global variables.

func New

func New() (UUID, error)

New generates a new UUIDv7 using the default generator. This is a convenience function that uses the package-level generator.

func NewV7

func NewV7() (UUID, error)

NewV7 is an alias for New() for explicit version specification

func Parse

func Parse(s string) (UUID, error)

Parse parses a UUID from its string representation. It accepts the following formats:

  • xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (canonical)
  • urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  • {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
  • xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx (without hyphens)

func (UUID) Bytes

func (u UUID) Bytes() []byte

Bytes returns the UUID as a byte slice

func (UUID) Compare

func (u UUID) Compare(other UUID) int

Compare returns an integer comparing two UUIDs lexicographically. The result will be 0 if u==other, -1 if u < other, and +1 if u > other.

func (UUID) EncodeToBase64

func (u UUID) EncodeToBase64() string

EncodeToBase64 encodes the UUID to a base64 string (URL-safe, no padding)

func (UUID) EncodeToBase64Std

func (u UUID) EncodeToBase64Std() string

EncodeToBase64Std encodes the UUID to a standard base64 string

func (UUID) EncodeToHex

func (u UUID) EncodeToHex() string

EncodeToHex encodes the UUID to a hexadecimal string without hyphens

func (UUID) Equal

func (u UUID) Equal(other UUID) bool

Equal returns true if u and other represent the same UUID

func (UUID) IsNil

func (u UUID) IsNil() bool

IsNil returns true if the UUID is the nil UUID (all zeros)

func (UUID) MarshalBinary

func (u UUID) MarshalBinary() ([]byte, error)

MarshalBinary implements the encoding.BinaryMarshaler interface

func (UUID) MarshalText

func (u UUID) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface

func (*UUID) Scan

func (u *UUID) Scan(src interface{}) error

Scan implements the sql.Scanner interface for database compatibility

func (UUID) String

func (u UUID) String() string

String returns the canonical string representation of the UUID in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

func (UUID) Time

func (u UUID) Time() time.Time

Time returns the timestamp as a time.Time for UUIDv7

func (UUID) Timestamp

func (u UUID) Timestamp() int64

Timestamp extracts the Unix timestamp (in milliseconds) from a UUIDv7

func (*UUID) UnmarshalBinary

func (u *UUID) UnmarshalBinary(data []byte) error

UnmarshalBinary implements the encoding.BinaryUnmarshaler interface

func (*UUID) UnmarshalText

func (u *UUID) UnmarshalText(data []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface

func (UUID) Value

func (u UUID) Value() (driver.Value, error)

Value implements the driver.Valuer interface for database compatibility

func (UUID) Variant

func (u UUID) Variant() Variant

Variant returns the variant of the UUID

func (UUID) Version

func (u UUID) Version() Version

Version returns the version of the UUID

type Variant

type Variant byte

Variant represents the UUID variant

const (
	VariantNCS Variant = iota
	VariantRFC4122
	VariantMicrosoft
	VariantFuture
)

type Version

type Version byte

Version represents the UUID version

const (
	VersionTimeBased Version
	VersionDCESecurity
	VersionNameBasedMD5
	VersionRandom
	VersionNameBasedSHA1

	VersionTimeSorted // UUIDv7
	VersionCustom     // UUIDv8
)

Directories

Path Synopsis
others
leafSegment command
leafSnowflake command

Jump to

Keyboard shortcuts

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