Reputation: 65
I am creating a C wrapper that can read types of data structures stored in text files. The interface should be that I can generate a unique id mapped to a unique data structure and modify through wrapper functions via the unique id.
The problem is that I need to be able to generate a unique id to map. I would like to not use any external library. Is there any way to do this without any large overhead?
Upvotes: 1
Views: 13479
Reputation: 1
I guess that you are wanting the id to be (practically speaking) world-wide unique (so two processes running your program on two different computers on two different machines would always have different ids).
Otherwise, just use a static long counter;
then id = counter++;
in your wrapper.
You might use UUIDs for that purpose.
Or you could generate a random -e.g. 24 bytes- string (or two or three random uint64_t
numbers). If your numbers are "enough" random (at least if you seed a good PRNG with a random seed at startup time, e.g. using a random source à la random(4) (or getrandom(2)) or the current time & process id & host id; be sure to use a PRNG with a big enough state) the probability of collisions should be negligible (but I am not able or willing to quantify it).
FWIW, in my MELT monitor, I am doing similar things (on Linux) in routine mom_make_random_idstr
of my file random.c; the random string contains a nicely restricted set of characters (compatible with C identifiers). Look also inside Bismon's id_BM.c file and the randomid_BM
& idtocbuf32_BM
or inside RefPerSys.
You could also take some inspiration from MongoDb objids.
See also this related question.
Upvotes: 4