xref: /qemu/util/id.c (revision 7a4e543d)
1 /*
2  * Dealing with identifiers
3  *
4  * Copyright (C) 2014 Red Hat, Inc.
5  *
6  * Authors:
7  *  Markus Armbruster <armbru@redhat.com>,
8  *
9  * This work is licensed under the terms of the GNU LGPL, version 2.1
10  * or later.  See the COPYING.LIB file in the top-level directory.
11  */
12 
13 #include "qemu/osdep.h"
14 #include "qemu-common.h"
15 
16 bool id_wellformed(const char *id)
17 {
18     int i;
19 
20     if (!qemu_isalpha(id[0])) {
21         return false;
22     }
23     for (i = 1; id[i]; i++) {
24         if (!qemu_isalnum(id[i]) && !strchr("-._", id[i])) {
25             return false;
26         }
27     }
28     return true;
29 }
30 
31 #define ID_SPECIAL_CHAR '#'
32 
33 static const char *const id_subsys_str[ID_MAX] = {
34     [ID_QDEV]  = "qdev",
35     [ID_BLOCK] = "block",
36 };
37 
38 /*
39  *  Generates an ID of the form PREFIX SUBSYSTEM NUMBER
40  *  where:
41  *
42  *  - PREFIX is the reserved character '#'
43  *  - SUBSYSTEM identifies the subsystem creating the ID
44  *  - NUMBER is a decimal number unique within SUBSYSTEM.
45  *
46  *    Example: "#block146"
47  *
48  * Note that these IDs do not satisfy id_wellformed().
49  *
50  * The caller is responsible for freeing the returned string with g_free()
51  */
52 char *id_generate(IdSubSystems id)
53 {
54     static uint64_t id_counters[ID_MAX];
55     uint32_t rnd;
56 
57     assert(id < ARRAY_SIZE(id_subsys_str));
58     assert(id_subsys_str[id]);
59 
60     rnd = g_random_int_range(0, 100);
61 
62     return g_strdup_printf("%c%s%" PRIu64 "%02" PRId32, ID_SPECIAL_CHAR,
63                                                         id_subsys_str[id],
64                                                         id_counters[id]++,
65                                                         rnd);
66 }
67