id.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. };
  33. /*
  34. * Generates an ID of the form PREFIX SUBSYSTEM NUMBER
  35. * where:
  36. *
  37. * - PREFIX is the reserved character '#'
  38. * - SUBSYSTEM identifies the subsystem creating the ID
  39. * - NUMBER is a decimal number unique within SUBSYSTEM.
  40. *
  41. * Example: "#block146"
  42. *
  43. * Note that these IDs do not satisfy id_wellformed().
  44. *
  45. * The caller is responsible for freeing the returned string with g_free()
  46. */
  47. char *id_generate(IdSubSystems id)
  48. {
  49. static uint64_t id_counters[ID_MAX];
  50. uint32_t rnd;
  51. assert(id < ARRAY_SIZE(id_subsys_str));
  52. assert(id_subsys_str[id]);
  53. rnd = g_random_int_range(0, 100);
  54. return g_strdup_printf("%c%s%" PRIu64 "%02" PRId32, ID_SPECIAL_CHAR,
  55. id_subsys_str[id],
  56. id_counters[id]++,
  57. rnd);
  58. }