48 lines
1.7 KiB
Go
48 lines
1.7 KiB
Go
// Package ulid provides thread-safe ULID (Universally Unique Lexicographically Sortable Identifier) generation.
|
|
//
|
|
// ULIDs are 128-bit identifiers that are lexicographically sortable and contain
|
|
// a timestamp component. This package uses cryptographically secure random
|
|
// generation optimized for simplicity and performance in concurrent environments.
|
|
package ulid
|
|
|
|
import (
|
|
cryptorand "crypto/rand"
|
|
"time"
|
|
|
|
oklid "github.com/oklog/ulid/v2"
|
|
)
|
|
|
|
// MakeULID generates a new ULID with the specified timestamp using cryptographically secure randomness.
|
|
// The function is thread-safe and optimized for high-concurrency environments.
|
|
//
|
|
// This implementation prioritizes simplicity and performance over strict monotonicity within
|
|
// the same millisecond. Each ULID is guaranteed to be unique and lexicographically sortable
|
|
// across different timestamps.
|
|
//
|
|
// Returns a pointer to the generated ULID or an error if generation fails.
|
|
// Generation should only fail under extreme circumstances (entropy exhaustion).
|
|
func MakeULID(t time.Time) (*oklid.ULID, error) {
|
|
id, err := oklid.New(oklid.Timestamp(t), cryptorand.Reader)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &id, nil
|
|
}
|
|
|
|
// Make generates a new ULID with the current timestamp using cryptographically secure randomness.
|
|
// This is a convenience function equivalent to MakeULID(time.Now()).
|
|
//
|
|
// The function is thread-safe and optimized for high-concurrency environments.
|
|
//
|
|
// Returns a pointer to the generated ULID or an error if generation fails.
|
|
// Generation should only fail under extreme circumstances (entropy exhaustion).
|
|
func Make() (*oklid.ULID, error) {
|
|
id, err := oklid.New(oklid.Now(), cryptorand.Reader)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &id, nil
|
|
}
|