Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a unique id in Ada?

I'm a working on a Ada project, I'm trying to generate a unique ID that will serve as the unique identifier of a person. I wonder if there is a way to generate a unique ID in Ada?


2 Answers

You really didn't specify a lot of requirements, so if you just need something quick and easy, you can use a private package variable and have a generator function return the current value and then update it to a new value.

with Ada.Text_IO; use Ada.Text_IO;

procedure Hello is

    package IDs is
        type ID is mod 2**64;
        function New_ID return ID;
    end IDs;

    package body IDs is
        Current : ID := 0;
        function New_ID return ID is
        begin
            return Result : ID := Current do
                Current := Current + 1;
            end return;
        end New_ID;
    end IDs;
begin
   Put_Line("Hello, world!");
   Put_Line("New ID =>" &  IDs.ID'Image(IDs.New_ID));
   Put_Line("New ID =>" &  IDs.ID'Image(IDs.New_ID));
end Hello;

Output:

$gnatmake -o hello *.adb
gcc -c hello.adb
gnatbind -x hello.ali
gnatlink hello.ali -o hello
$hello
Hello, world!
New ID => 0
New ID => 1

If you need it task safe, then wrap the "Current" variable in a protected object. It will only generate up to 2**64 unique IDs, but you can change that if your compiler supports larger data types.

like image 174
Jere Avatar answered Sep 07 '25 23:09

Jere


Package PragmARC.Job_Pools does this, so you might want to look at it.

PragmARC.Job_Pools

like image 23
Jeffrey R. Carter Avatar answered Sep 07 '25 23:09

Jeffrey R. Carter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!