I want to generate a v5 UUID for a string using a given namespace.
https://man.archlinux.org/man/uuid_generate_time.3.en talks about uuid_generate_sha1()
but I could not find any good examples on how to use them in our code.
My pseudocode looks like:
_generate_v5_uuid(const char *inputStr, const char *namespace, char **outputString)
{
uuid_t uuid;
uuid_generate_sha1(inputStr, &uuid);
*outputStr = convert_uuid_to_string(uuid);
return;
}
What exactly needs to be passed to uuid_generate_sha1
?
CodePudding user response:
I have written this example for you:
#include <uuid/uuid.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *convert_uuid_to_string(uuid_t uuid) {
char *buf = NULL;
size_t s = 0;
FILE *f = open_memstream(&buf, &s);
for (size_t i = 0; i < 16; i) {
fprintf(f, "x", uuid[i]);
}
fclose(f);
return buf;
}
char *generate_v5_uuid(const char *inputStr, const char *namespace) {
const uuid_t *ns = uuid_get_template(&namespace[1]);
uuid_t uuid;
uuid_generate_sha1(uuid, *ns, inputStr, strlen(inputStr));
return convert_uuid_to_string(uuid);
}
int main() {
system("set -x ; uuidgen --sha1 -n @url -N string");
printf("%s\n", generate_v5_uuid("string", "@url"));
}
The program outputs:
$ ./a.out
uuidgen --sha1 -n @url -N string
64be9091-88e8-5476-996b-8b541f7bf3e5
64be909188e85476996b8b541f7bf3e5
CodePudding user response:
char *generate_v5_uuid(const char *inputStr, const char *namespace)
{
uuid_t ns;
uuid_parse(namespace, ns);
uuid_t uuid;
uuid_generate_sha1(uuid, ns, inputStr, strlen(inputStr));
return convert_uuid_to_string(uuid);
}