nanoid-net Documentation

repository·master·Indexed 20 days ago

https://github.com/codeyu/nanoid-net

A .NET implementation of the NanoID library for generating compact, URL-friendly, and cryptographically secure unique identifiers. Supports custom lengths, custom alphabets, and thread-safe random generation using System.Security.Cryptography.RandomNumberGenerator.

Tokens
637
Snippets
4
Records
4
Agent score
19%

What's inside nanoid-net

  1. How thread safety and random generation work in Nanoid

    master

    Nanoid uses a cryptographically strong random generator by default.

    Default Behavior

    It uses an internal [ThreadStatic] wrapper over System.Security.Cryptography.RandomNumberGenerator. This creates a separate instance of the generator per thread, ensuring thread safety without the performance overhead of locks.

    Custom Random Generators

    You can provide your own random generator (e.g., System.Random) to Nanoid.Generate. This is useful for seed-based generation.

    Warning: If you provide a global random generator, you are responsible for managing its thread safety.

    Preloading the Global Generator

    The global random generator is lazily initialized. To force initialization on the current thread immediately, access the Nanoid.GlobalRandom getter.

    // Using a seed-based System.Random generator
    var random = new Random(10);
    var id = Nanoid.Generate(random, Nanoid.Alphabets.Letters, 10); //=> "fbAeFaaDeb"
  2. Generate a default Nanoid

    master

    Use Nanoid.Generate() to create a default ID. By default, it uses URL-friendly symbols (A-Za-z0-9_-) and returns a 21-character string, providing a collision probability similar to UUID v4.

    var id = Nanoid.Generate(); //=> "Uakgb_J5m9g-0JDMbcJqLJ"
  3. Generate Nanoids with custom length or alphabet

    master

    You can customize the ID by specifying a custom length or a specific alphabet.

    • To change only the length, pass the size argument.
    • To change both, pass an alphabet string and a size integer.
    • Predefined alphabets are available in the Nanoid.Alphabets class.
    // Custom length
    var id = Nanoid.Generate(size: 10); //=> "IRFa-VaY2b"
    
    // Custom alphabet and length using predefined Alphabets
    var id1 = Nanoid.Generate(Nanoid.Alphabets.LowercaseLettersAndDigits, 10); //=> "4f90d13a42"
    
    // Custom alphabet and length using a string
    var id2 = Nanoid.Generate("1234567890abcdef", 5); //=> "2x501"