Documentation ¶
Index ¶
Constants ¶
const ( // DefaultAlphabet defines the standard set of characters used for Nano ID generation. // It includes uppercase and lowercase English letters, digits, and the characters // '_' and '-'. This selection aligns with the Nano ID specification, ensuring // a URL-friendly and easily readable identifier. // // Example: "_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" DefaultAlphabet = "_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" // DefaultLength specifies the default number of characters in a generated Nano ID. // A length of 21 characters provides a high level of uniqueness while maintaining // brevity, making it suitable for most applications requiring unique identifiers. DefaultLength = 21 // MinAlphabetLength sets the minimum permissible number of unique characters // in the alphabet used for Nano ID generation. An alphabet with fewer than // 2 characters would not provide sufficient variability for generating unique IDs, // making this a lower bound to ensure meaningful ID generation. // // Example: An alphabet like "AB" is acceptable, but "A" is not. MinAlphabetLength = 2 // MaxAlphabetLength defines the maximum allowable number of unique characters // in the alphabet for Nano ID generation. This upper limit ensures that the // generator operates within reasonable memory and performance constraints, // preventing excessively large alphabets that could degrade performance or // complicate index calculations. MaxAlphabetLength = 256 )
Variables ¶
var ( // ErrDuplicateCharacters is returned when the provided alphabet contains duplicate characters. ErrDuplicateCharacters = errors.New("duplicate characters in alphabet") // ErrExceededMaxAttempts is returned when the maximum number of attempts to perform // an operation, such as generating a unique ID, has been exceeded. ErrExceededMaxAttempts = errors.New("exceeded maximum attempts") // ErrInvalidLength is returned when a specified length value for an operation is invalid. ErrInvalidLength = errors.New("invalid length") // ErrInvalidAlphabet is returned when the provided alphabet for generating IDs is invalid. ErrInvalidAlphabet = errors.New("invalid alphabet") // ErrNonUTF8Alphabet is returned when the provided alphabet contains non-UTF-8 characters. ErrNonUTF8Alphabet = errors.New("alphabet contains invalid UTF-8 characters") // ErrAlphabetTooShort is returned when the provided alphabet has fewer than 2 characters. ErrAlphabetTooShort = errors.New("alphabet length is less than 2") // ErrAlphabetTooLong is returned when the provided alphabet exceeds 256 characters. ErrAlphabetTooLong = errors.New("alphabet length exceeds 256") // ErrNilRandReader is returned when the random number generator (rand.Reader) is nil, // preventing the generation of random values. ErrNilRandReader = errors.New("nil random reader") // ErrNilPointer is returned when a nil pointer is passed to a function that does not accept nil pointers. ErrNilPointer = errors.New("nil pointer") )
var EmptyID = ID("")
EmptyID represents an empty Nano ID.
Functions ¶
func Read ¶ added in v1.14.0
Read reads up to len(p) bytes into p. It returns the number of bytes read (0 <= n <= len(p)) and any error encountered. Even if Read returns n < len(p), it may use all of p as scratch space during the call. If some data is available but not len(p) bytes, Read conventionally returns what is available instead of waiting for more.
Reader is the interface that wraps the basic Read method.
When Read encounters an error or end-of-file condition after successfully reading n > 0 bytes, it returns the number of bytes read. It may return the (non-nil) error from the same call or return the error (and n == 0) from a subsequent call. An instance of this general case is that a Reader returning a non-zero number of bytes at the end of the input stream may return either err == EOF or err == nil. The next Read should return 0, EOF.
Callers should always process the n > 0 bytes returned before considering the error err. Doing so correctly handles I/O errors that happen after reading some bytes and also both of the allowed EOF behaviors.
If len(p) == 0, Read should always return n == 0. It may return a non-nil error if some error condition is known, such as EOF.
Implementations of Read are discouraged from returning a zero byte count with a nil error, except when len(p) == 0. Callers should treat a return of 0 and nil as indicating that nothing happened; in particular it does not indicate EOF.
Implementations must not retain p.
Types ¶
type Config ¶ added in v1.5.0
type Config interface { // AlphabetLen returns the number of unique characters in the provided alphabet. // // This length determines the range of indices for selecting characters during ID generation. // Using uint16 allows for alphabets up to 65,535 characters. AlphabetLen() uint16 // BaseMultiplier returns the foundational multiplier used in buffer size calculations. // // It is based on the logarithm of the intended ID length (LengthHint) plus 2. // This helps scale the buffer size appropriately with different ID lengths. BaseMultiplier() int // BitsNeeded returns the minimum number of bits required to represent all possible indices of the alphabet. // // This value is crucial for generating random numbers that map uniformly to the alphabet indices without bias. BitsNeeded() uint // BufferMultiplier returns the combined multiplier used in the buffer size calculation. // // It adds a fraction of the scaling factor to the base multiplier to fine-tune the buffer size, // considering both the ID length and the alphabet size. BufferMultiplier() int // BufferSize returns the total size of the buffer (in bytes) used for generating random data. // // The buffer size is calculated to balance efficiency and performance, // minimizing calls to the random number generator by reading larger chunks of random data at once. BufferSize() int // ByteAlphabet returns the slice of bytes representing the alphabet, // used when the alphabet consists solely of ASCII characters. // // For non-ASCII alphabets, this returns nil, and RuneAlphabet is used instead. ByteAlphabet() []byte // BytesNeeded returns the number of bytes required to store the BitsNeeded for each character in the ID. // // It rounds up BitsNeeded to the nearest byte, ensuring sufficient space for random data generation. BytesNeeded() uint // IsASCII returns true if the alphabet consists solely of ASCII characters. // // This allows for optimization in processing, using bytes instead of runes for ID generation. IsASCII() bool // IsPowerOfTwo returns true if the length of the alphabet is a power of two. // // When true, random index selection can be optimized using bitwise operations, // such as bitwise AND with the mask, improving performance. IsPowerOfTwo() bool // LengthHint returns the intended length of the IDs to be generated. // // This hint is used in calculations to adjust buffer sizes and scaling factors accordingly. LengthHint() uint16 // MaxBytesPerRune represents the maximum number of bytes required to encode // any rune in the alphabet using UTF-8 encoding. // // This value is computed during // configuration based on the provided alphabet and is used to preallocate the // buffer size in the newUnicode function. By accurately estimating the buffer size, // we ensure efficient string building without unnecessary memory allocations // or buffer resizing. // // For example, if the alphabet includes only ASCII and Latin-1 characters, each rune // requires at most 2 bytes. However, if the alphabet includes emojis or other // multibyte characters, this value could be up to 4 bytes. MaxBytesPerRune() int // Mask returns the bitmask used to extract the necessary bits from randomly generated bytes. // // The mask is essential for efficiently mapping random values to valid alphabet indices, // ensuring uniform distribution and preventing bias. Mask() uint // RandReader returns the source of randomness used for generating IDs. // // It is typically a cryptographically secure random number generator (e.g., crypto/rand.Reader). RandReader() io.Reader // RuneAlphabet returns the slice of runes representing the alphabet. // // This is used for ID generation when the alphabet includes non-ASCII (multibyte) characters, // allowing support for a wider range of characters. RuneAlphabet() []rune // ScalingFactor returns the scaling factor used to adjust the buffer size. // // It balances the influence of the alphabet size and the intended ID length, // ensuring efficient random data generation without excessive memory usage. ScalingFactor() int }
Config holds the runtime configuration for the Nano ID generator.
It is immutable after initialization and provides all the necessary parameters for generating unique IDs efficiently and securely.
type ConfigOptions ¶ added in v1.10.0
type ConfigOptions struct { // RandReader is the source of randomness used for generating IDs. // By default, it uses x/crypto/prng/Reader, which provides cryptographically secure random bytes. RandReader io.Reader // Alphabet is the set of characters used to generate the Nano ID. // It must be a valid UTF-8 string containing between 2 and 256 unique characters. // Using a diverse and appropriately sized alphabet ensures the uniqueness and randomness of the generated IDs. Alphabet string // LengthHint specifies a typical or default length for generated IDs. LengthHint uint16 }
ConfigOptions holds the configurable options for the Interface. It is used with the Function Options pattern.
type Configuration ¶ added in v1.5.0
type Configuration interface { // Config returns the runtime configuration of the generator. Config() Config }
Configuration defines the interface for retrieving generator configuration.
type ID ¶ added in v1.18.0
type ID string
ID represents a Nano ID as a string.
func Must ¶ added in v1.10.0
func Must() ID
Must generates a new Nano ID using the default length specified by `DefaultLength`. It returns the generated ID as a string. If an error occurs during ID generation, it panics. This function simplifies safe initialization of global variables holding pre-generated Nano IDs.
Usage:
id := nanoid.Must() fmt.Println("Generated ID:", id)
func MustWithLength ¶ added in v1.10.0
MustWithLength generates a new Nano ID of the specified length. It returns the generated ID as a string. If an error occurs during ID generation, it panics. The 'length' parameter specifies the number of characters in the generated ID. This function simplifies safe initialization of global variables holding pre-generated Nano IDs.
Parameters:
- length int: The number of characters for the generated ID.
Usage:
id := nanoid.MustWithLength(30) fmt.Println("Generated ID:", id)
func New ¶ added in v1.3.0
New generates a new Nano ID using the default length specified by `DefaultLength`. It returns the generated ID as a string and any error encountered during the generation.
Usage:
id, err := nanoid.New() if err != nil { // handle error } fmt.Println("Generated ID:", id)
func NewWithLength ¶ added in v1.10.0
NewWithLength generates a new Nano ID of the specified length. It returns the generated ID as a string and any error encountered during the generation.
Parameters:
- length int: The number of characters for the generated ID.
Usage:
id, err := nanoid.NewWithLength(21) if err != nil { // handle error } fmt.Println("Generated ID:", id)
func (*ID) Compare ¶ added in v1.18.0
Compare compares two IDs lexicographically and returns an integer. The result will be 0 if id==other, -1 if id < other, and +1 if id > other.
Parameters:
- other ID: The ID to compare against.
Returns:
- int: An integer indicating the comparison result.
Usage:
id1 := ID("V1StGXR8_Z5jdHi6B-myT") id2 := ID("V1StGXR8_Z5jdHi6B-myT") result := id1.Compare(id2) fmt.Println(result) // Output: 0
func (*ID) MarshalBinary ¶ added in v1.18.0
MarshalBinary converts the ID to a byte slice. It implements the encoding.BinaryMarshaler interface, enabling the ID to be marshaled into binary formats for efficient storage or transmission.
Returns:
- A byte slice containing the ID.
- An error if the marshaling fails.
Example:
id := Must() binaryData, err := id.MarshalBinary() if err != nil { log.Fatal(err) } fmt.Println(binaryData) // Output: [86 49 83 116 71 88 82 56 95 90 ...]
func (*ID) MarshalText ¶ added in v1.18.0
MarshalText converts the ID to a byte slice. It implements the encoding.TextMarshaler interface, enabling the ID to be marshaled into text-based formats such as XML and YAML.
Returns:
- A byte slice containing the ID.
- An error if the marshaling fails.
Example:
id := Must() text, err := id.MarshalText() if err != nil { log.Fatal(err) } fmt.Println(string(text)) // Output: V1StGXR8_Z5jdHi6B-myT
func (*ID) String ¶ added in v1.18.0
String returns the string representation of the ID. It implements the fmt.Stringer interface, allowing the ID to be used seamlessly with fmt package functions like fmt.Println and fmt.Printf.
Example:
id := Must() fmt.Println(id) // Output: V1StGXR8_Z5jdHi6B-myT
func (*ID) UnmarshalBinary ¶ added in v1.18.0
UnmarshalBinary parses a byte slice and assigns the result to the ID. It implements the encoding.BinaryUnmarshaler interface, allowing the ID to be unmarshaled from binary formats.
Parameters:
- data: A byte slice containing the binary ID data.
Returns:
- An error if the unmarshaling fails.
Example:
var id ID err := id.UnmarshalBinary([]byte{86, 49, 83, 116, 71, 88, 82, 56, 95, 90}) // "V1StGXR8_Z5jdHi6B-myT" if err != nil { log.Fatal(err) } fmt.Println(id) // Output: V1StGXR8_Z5jdHi6B-myT
func (*ID) UnmarshalText ¶ added in v1.18.0
UnmarshalText parses a byte slice and assigns the result to the ID. It implements the encoding.TextUnmarshaler interface, allowing the ID to be unmarshaled from text-based formats.
Parameters:
- text: A byte slice containing the ID data.
Returns:
- An error if the unmarshaling fails.
Example:
var id ID err := id.UnmarshalText([]byte("new-id")) if err != nil { log.Fatal(err) } fmt.Println(id) // Output: new-id
type Interface ¶ added in v1.21.0
type Interface interface { // New generates and returns a new Nano ID as a string with the specified length. // The 'length' parameter determines the number of characters in the generated ID. // Returns an error if the ID generation fails due to issues like insufficient randomness. // // Usage: // id, err := generator.New(21) // if err != nil { // // handle error // } // fmt.Println("Generated ID:", id) New(length int) (ID, error) // Read fills the provided byte slice 'p' with random data, reading up to len(p) bytes. // Returns the number of bytes read and any error encountered during the read operation. // // Implements the io.Reader interface, allowing the Interface to be used wherever an io.Reader is accepted. // This can be useful for directly obtaining random bytes or integrating with other components that consume random data. // // Usage: // buffer := make([]byte, 21) // n, err := generator.Read(buffer) // if err != nil { // // handle error // } // fmt.Printf("Read %d random bytes\n", n) Read(b []byte) (n int, err error) }
Interface defines the contract for generating Nano IDs.
Implementations of this interface provide methods to create new IDs and to read random data, supporting both ID generation and direct random byte access.
func NewGenerator ¶ added in v1.10.0
NewGenerator creates a new Interface with buffer pooling enabled. It accepts variadic Option parameters to configure the Interface's behavior. The function initializes the configuration with default values, applies any provided options, validates the configuration, constructs the runtime configuration, initializes buffer pools, and returns a configured Interface or an error if the configuration is invalid.
Parameters:
- options ...Option: A variadic list of Option functions to customize the Interface's configuration.
Returns:
- Interface: An instance of the Interface interface configured with the specified options.
- error: An error object if the Interface could not be created due to invalid configuration.
Error Conditions:
- ErrInvalidLength: Returned if the provided LengthHint is less than 1.
- ErrNilRandReader: Returned if the provided RandReader is nil.
- ErrInvalidAlphabet: Returned if the alphabet is invalid or contains invalid UTF-8 characters.
- ErrNonUTF8Alphabet: Returned if the alphabet contains non-UTF-8 characters.
- ErrDuplicateCharacters: Returned if the alphabet contains duplicate characters.
type Option ¶ added in v1.10.0
type Option func(*ConfigOptions)
Option defines a function type for configuring the Interface. It allows for flexible and extensible configuration by applying various settings to the ConfigOptions during Interface initialization.
func WithAlphabet ¶ added in v1.10.0
WithAlphabet sets a custom alphabet for the Interface. The provided alphabet string defines the set of characters that will be used to generate Nano IDs. This allows users to customize the character set according to their specific requirements, such as using only alphanumeric characters, including symbols, or supporting non-ASCII characters.
Parameters:
- alphabet string: A string representing the desired set of characters for ID generation.
Returns:
- Option: A configuration option that applies the custom alphabet to ConfigOptions.
Usage:
generator, err := nanoid.NewGenerator(nanoid.WithAlphabet("abcdef123456"))
func WithLengthHint ¶ added in v1.12.0
WithLengthHint sets the hint of the intended length of the IDs to be generated. Providing a length hint allows the Interface to optimize internal configurations, such as buffer sizes and scaling factors, based on the expected ID length. This can enhance performance and efficiency, especially when generating a large number of IDs with similar lengths.
Parameters:
- hint uint16: A non-zero unsigned integer representing the anticipated length of the Nano IDs.
Returns:
- Option: A configuration option that applies the length hint to ConfigOptions.
Usage Example:
generator, err := nanoid.NewGenerator(nanoid.WithLengthHint(21))
func WithRandReader ¶ added in v1.10.0
WithRandReader sets a custom random reader for the Interface. By default, the Interface uses a cryptographically secure random number generator (e.g., crypto/rand.Reader). However, in some cases, users might want to provide their own source of randomness, such as for testing purposes or to integrate with a different entropy source.
Parameters:
- reader io.Reader: An implementation of io.Reader that supplies random data.
Returns:
- Option: A configuration option that applies the custom random reader to ConfigOptions.
Usage Example:
customReader := myCustomRandomReader() generator, err := nanoid.NewGenerator( nanoid.WithRandReader(customReader))