uuid.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright 2011 Calxeda, Inc.
  3. *
  4. * SPDX-License-Identifier: GPL-2.0+
  5. */
  6. #include <linux/ctype.h>
  7. #include "common.h"
  8. /*
  9. * This is what a UUID string looks like.
  10. *
  11. * x is a hexadecimal character. fields are separated by '-'s. When converting
  12. * to a binary UUID, le means the field should be converted to little endian,
  13. * and be means it should be converted to big endian.
  14. *
  15. * 0 9 14 19 24
  16. * xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  17. * le le le be be
  18. */
  19. int uuid_str_valid(const char *uuid)
  20. {
  21. int i, valid;
  22. if (uuid == NULL)
  23. return 0;
  24. for (i = 0, valid = 1; uuid[i] && valid; i++) {
  25. switch (i) {
  26. case 8: case 13: case 18: case 23:
  27. valid = (uuid[i] == '-');
  28. break;
  29. default:
  30. valid = isxdigit(uuid[i]);
  31. break;
  32. }
  33. }
  34. if (i != 36 || !valid)
  35. return 0;
  36. return 1;
  37. }
  38. void uuid_str_to_bin(const char *uuid, unsigned char *out)
  39. {
  40. uint16_t tmp16;
  41. uint32_t tmp32;
  42. uint64_t tmp64;
  43. if (!uuid || !out)
  44. return;
  45. tmp32 = cpu_to_le32(simple_strtoul(uuid, NULL, 16));
  46. memcpy(out, &tmp32, 4);
  47. tmp16 = cpu_to_le16(simple_strtoul(uuid + 9, NULL, 16));
  48. memcpy(out + 4, &tmp16, 2);
  49. tmp16 = cpu_to_le16(simple_strtoul(uuid + 14, NULL, 16));
  50. memcpy(out + 6, &tmp16, 2);
  51. tmp16 = cpu_to_be16(simple_strtoul(uuid + 19, NULL, 16));
  52. memcpy(out + 8, &tmp16, 2);
  53. tmp64 = cpu_to_be64(simple_strtoull(uuid + 24, NULL, 16));
  54. memcpy(out + 10, (char *)&tmp64 + 2, 6);
  55. }