Generate Nanoids in Delphi

Resources  |  Generate Nanoids in Delphi

Generating a Nanoid in Delphi involves creating a function that can produce a URL-safe, compact, and unique identifier. Delphi (also known as Object Pascal) is a high-level language that can efficiently handle such tasks. Here's how you can implement Nanoid generation in Delphi:

Example Code

Here is a Delphi function to generate a Nanoid:

uses
  System.SysUtils, System.Classes, System.Math, System.Types;

function GenerateNanoid(Length: Integer): string;
const
  Alphabet: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
var
  Nanoid: TStringBuilder;
  Buffer: TBytes;
  I, Index: Integer;
begin
  Nanoid := TStringBuilder.Create;
  try
    SetLength(Buffer, Length);
    // Fill buffer with random bytes
    TNetEncoding.Base64.Decode(TNetEncoding.Base64.Encode(THashSHA2.GetHashBytes(Alphabet)), Buffer);

    for I := 0 to Length - 1 do
    begin
      // Map each byte to a character in the alphabet
      Index := Buffer[I] mod Length(Alphabet);
      Nanoid.Append(Alphabet[Index + 1]);
    end;

    Result := Nanoid.ToString;
  finally
    Nanoid.Free;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  Nanoid: string;
begin
  Nanoid := GenerateNanoid(21); // Generate a Nanoid of length 21
  ShowMessage('Generated Nanoid: ' + Nanoid);
end;

Explanation

  1. Alphabet:

    • The Alphabet constant string contains characters that the Nanoid will consist of. It includes uppercase letters, lowercase letters, digits, and the symbols '-' and '_'.
  2. Buffer:

    • The Buffer array holds random bytes. The length of the buffer is equal to the desired length of the Nanoid.
  3. Random Byte Generation:

    • TNetEncoding.Base64.Decode(TNetEncoding.Base64.Encode(THashSHA2.GetHashBytes(Alphabet)), Buffer): This line generates random bytes. We use Base64 encoding and decoding to simulate randomness. Alternatively, you can use other Delphi libraries for generating random bytes, such as TIdHashSHA1.
  4. Nanoid Construction:

    • The function iterates through the buffer, mapping each byte to a character in the alphabet and appending it to the Nanoid string builder.
  5. Result:

    • The generated Nanoid is returned as a string.

Usage

  1. Create a New Delphi Application:

    • Open Delphi and create a new VCL Forms Application.
  2. Add a Button to the Form:

    • Place a button on the form (e.g., Button1).
  3. Add the Example Code:

    • Add the provided code to the form's unit. Make sure to include the necessary uses clauses (System.SysUtils, System.Classes, System.Math, System.Types).
  4. Run the Application:

    • Run the application and click the button to generate and display a Nanoid.

Customization

  • Alphabet: Modify the Alphabet constant if you need a different set of characters.
  • Length: Change the Length parameter in the GenerateNanoid function call to generate Nanoids of different lengths.

Considerations

  • Randomness: The example uses a workaround to generate randomness by hashing and encoding. For better randomness, you can use a proper random byte generator library.
  • Error Handling: Add error handling for scenarios where the Nanoid generation might fail.

By following this example, you can generate Nanoids in Delphi, ensuring that your identifiers are unique, compact, and suitable for use in various applications.