uuid.c 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Copyright 2011 Calxeda, Inc.
  3. *
  4. * See file CREDITS for list of people who contributed to this
  5. * project.
  6. *
  7. * This program is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU General Public License as
  9. * published by the Free Software Foundation; either version 2 of
  10. * the License, or (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software
  19. * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  20. * MA 02111-1307 USA
  21. */
  22. #include <linux/ctype.h>
  23. #include "common.h"
  24. /*
  25. * This is what a UUID string looks like.
  26. *
  27. * x is a hexadecimal character. fields are separated by '-'s. When converting
  28. * to a binary UUID, le means the field should be converted to little endian,
  29. * and be means it should be converted to big endian.
  30. *
  31. * 0 9 14 19 24
  32. * xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
  33. * le le le be be
  34. */
  35. int uuid_str_valid(const char *uuid)
  36. {
  37. int i, valid;
  38. if (uuid == NULL)
  39. return 0;
  40. for (i = 0, valid = 1; uuid[i] && valid; i++) {
  41. switch (i) {
  42. case 8: case 13: case 18: case 23:
  43. valid = (uuid[i] == '-');
  44. break;
  45. default:
  46. valid = isxdigit(uuid[i]);
  47. break;
  48. }
  49. }
  50. if (i != 36 || !valid)
  51. return 0;
  52. return 1;
  53. }
  54. void uuid_str_to_bin(const char *uuid, unsigned char *out)
  55. {
  56. uint16_t tmp16;
  57. uint32_t tmp32;
  58. uint64_t tmp64;
  59. if (!uuid || !out)
  60. return;
  61. tmp32 = cpu_to_le32(simple_strtoul(uuid, NULL, 16));
  62. memcpy(out, &tmp32, 4);
  63. tmp16 = cpu_to_le16(simple_strtoul(uuid + 9, NULL, 16));
  64. memcpy(out + 4, &tmp16, 2);
  65. tmp16 = cpu_to_le16(simple_strtoul(uuid + 14, NULL, 16));
  66. memcpy(out + 6, &tmp16, 2);
  67. tmp16 = cpu_to_be16(simple_strtoul(uuid + 19, NULL, 16));
  68. memcpy(out + 8, &tmp16, 2);
  69. tmp64 = cpu_to_be64(simple_strtoull(uuid + 24, NULL, 16));
  70. memcpy(out + 10, (char *)&tmp64 + 2, 6);
  71. }