UUID.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /*
  2. * Copyright (c) 2020, Liav A. <liavalb@hotmail.co.il>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/AllOf.h>
  7. #include <AK/Hex.h>
  8. #include <AK/StringBuilder.h>
  9. #include <AK/UUID.h>
  10. namespace AK {
  11. UUID::UUID(Array<u8, 16> uuid_buffer)
  12. {
  13. uuid_buffer.span().copy_to(m_uuid_buffer);
  14. }
  15. void UUID::convert_string_view_to_uuid(StringView uuid_string_view)
  16. {
  17. VERIFY(uuid_string_view.length() == 36);
  18. auto first_unit = decode_hex(uuid_string_view.substring_view(0, 8));
  19. auto second_unit = decode_hex(uuid_string_view.substring_view(9, 4));
  20. auto third_unit = decode_hex(uuid_string_view.substring_view(14, 4));
  21. auto fourth_unit = decode_hex(uuid_string_view.substring_view(19, 4));
  22. auto fifth_unit = decode_hex(uuid_string_view.substring_view(24, 12));
  23. VERIFY(first_unit.value().size() == 4 && second_unit.value().size() == 2
  24. && third_unit.value().size() == 2 && fourth_unit.value().size() == 2
  25. && fifth_unit.value().size() == 6);
  26. m_uuid_buffer.span().overwrite(0, first_unit.value().data(), first_unit.value().size());
  27. m_uuid_buffer.span().overwrite(4, second_unit.value().data(), second_unit.value().size());
  28. m_uuid_buffer.span().overwrite(6, third_unit.value().data(), third_unit.value().size());
  29. m_uuid_buffer.span().overwrite(8, fourth_unit.value().data(), fourth_unit.value().size());
  30. m_uuid_buffer.span().overwrite(10, fifth_unit.value().data(), fifth_unit.value().size());
  31. }
  32. UUID::UUID(StringView uuid_string_view)
  33. {
  34. convert_string_view_to_uuid(uuid_string_view);
  35. }
  36. String UUID::to_string() const
  37. {
  38. StringBuilder builder(36);
  39. builder.append(encode_hex(m_uuid_buffer.span().trim(4)).view());
  40. builder.append('-');
  41. builder.append(encode_hex(m_uuid_buffer.span().slice(4).trim(2)).view());
  42. builder.append('-');
  43. builder.append(encode_hex(m_uuid_buffer.span().slice(6).trim(2)).view());
  44. builder.append('-');
  45. builder.append(encode_hex(m_uuid_buffer.span().slice(8).trim(2)).view());
  46. builder.append('-');
  47. builder.append(encode_hex(m_uuid_buffer.span().slice(10).trim(6)).view());
  48. return builder.to_string();
  49. }
  50. bool UUID::operator==(const UUID& other) const
  51. {
  52. for (size_t index = 0; index < 16; index++) {
  53. if (m_uuid_buffer[index] != other.m_uuid_buffer[index])
  54. return false;
  55. }
  56. return true;
  57. }
  58. bool UUID::is_zero() const
  59. {
  60. return all_of(m_uuid_buffer, [](const auto octet) { return octet == 0; });
  61. }
  62. }