Serialize.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright (c) 2021, Jan de Visser <jan@de-visser.net>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/ByteBuffer.h>
  8. #include <AK/Debug.h>
  9. #include <AK/Format.h>
  10. #include <AK/String.h>
  11. #include <string.h>
  12. namespace SQL {
  13. inline void dump(u8 const* ptr, size_t sz, String const& prefix)
  14. {
  15. StringBuilder builder;
  16. builder.appendff("{0} {1:04x} | ", prefix, sz);
  17. Vector<String> bytes;
  18. for (auto ix = 0u; ix < sz; ++ix) {
  19. bytes.append(String::formatted("{0:02x}", *(ptr + ix)));
  20. }
  21. StringBuilder bytes_builder;
  22. bytes_builder.join(" ", bytes);
  23. builder.append(bytes_builder.to_string());
  24. dbgln(builder.to_string());
  25. }
  26. inline void write(ByteBuffer& buffer, u8 const* ptr, size_t sz)
  27. {
  28. if constexpr (SQL_DEBUG)
  29. dump(ptr, sz, "->");
  30. buffer.append(ptr, sz);
  31. }
  32. inline u8* read(ByteBuffer& buffer, size_t& at_offset, size_t sz)
  33. {
  34. auto buffer_ptr = buffer.offset_pointer((int)at_offset);
  35. if constexpr (SQL_DEBUG)
  36. dump(buffer_ptr, sz, "<-");
  37. at_offset += sz;
  38. return buffer_ptr;
  39. }
  40. template<typename T>
  41. void deserialize_from(ByteBuffer& buffer, size_t& at_offset, T& t)
  42. {
  43. memcpy(&t, read(buffer, at_offset, sizeof(T)), sizeof(T));
  44. }
  45. template<typename T>
  46. void serialize_to(ByteBuffer& buffer, T const& t)
  47. {
  48. write(buffer, (u8 const*)(&t), sizeof(T));
  49. }
  50. template<>
  51. inline void deserialize_from<String>(ByteBuffer& buffer, size_t& at_offset, String& string)
  52. {
  53. u32 length;
  54. deserialize_from(buffer, at_offset, length);
  55. if (length > 0) {
  56. string = String((const char*)read(buffer, at_offset, length), length);
  57. } else {
  58. string = "";
  59. }
  60. }
  61. template<>
  62. inline void serialize_to<String>(ByteBuffer& buffer, String const& t)
  63. {
  64. u32 number_of_bytes = min(t.length(), 64);
  65. serialize_to(buffer, number_of_bytes);
  66. if (t.length() > 0) {
  67. write(buffer, (u8 const*)(t.characters()), number_of_bytes);
  68. }
  69. }
  70. }