2
0

id.c 1.6 KB

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