]> git.proxmox.com Git - mirror_qemu.git/blob - util/id.c
Merge remote-tracking branch 'remotes/mst/tags/for_upstream' into staging
[mirror_qemu.git] / util / id.c
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-common.h"
14
15 bool id_wellformed(const char *id)
16 {
17 int i;
18
19 if (!qemu_isalpha(id[0])) {
20 return false;
21 }
22 for (i = 1; id[i]; i++) {
23 if (!qemu_isalnum(id[i]) && !strchr("-._", id[i])) {
24 return false;
25 }
26 }
27 return true;
28 }
29
30 #define ID_SPECIAL_CHAR '#'
31
32 static const char *const id_subsys_str[] = {
33 [ID_QDEV] = "qdev",
34 [ID_BLOCK] = "block",
35 };
36
37 /*
38 * Generates an ID of the form PREFIX SUBSYSTEM NUMBER
39 * where:
40 *
41 * - PREFIX is the reserved character '#'
42 * - SUBSYSTEM identifies the subsystem creating the ID
43 * - NUMBER is a decimal number unique within SUBSYSTEM.
44 *
45 * Example: "#block146"
46 *
47 * Note that these IDs do not satisfy id_wellformed().
48 *
49 * The caller is responsible for freeing the returned string with g_free()
50 */
51 char *id_generate(IdSubSystems id)
52 {
53 static uint64_t id_counters[ID_MAX];
54 uint32_t rnd;
55
56 assert(id < ID_MAX);
57 assert(id_subsys_str[id]);
58
59 rnd = g_random_int_range(0, 100);
60
61 return g_strdup_printf("%c%s%" PRIu64 "%02" PRId32, ID_SPECIAL_CHAR,
62 id_subsys_str[id],
63 id_counters[id]++,
64 rnd);
65 }