Encoder.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Concepts.h>
  8. #include <AK/StdLibExtras.h>
  9. #include <LibIPC/Forward.h>
  10. #include <LibIPC/Message.h>
  11. namespace IPC {
  12. template<typename T>
  13. bool encode(Encoder&, T&)
  14. {
  15. static_assert(DependentFalse<T>, "Base IPC::encode() was instantiated");
  16. VERIFY_NOT_REACHED();
  17. }
  18. class Encoder {
  19. public:
  20. explicit Encoder(MessageBuffer& buffer)
  21. : m_buffer(buffer)
  22. {
  23. }
  24. Encoder& operator<<(bool);
  25. Encoder& operator<<(u8);
  26. Encoder& operator<<(u16);
  27. Encoder& operator<<(unsigned);
  28. Encoder& operator<<(unsigned long);
  29. Encoder& operator<<(unsigned long long);
  30. Encoder& operator<<(i8);
  31. Encoder& operator<<(i16);
  32. Encoder& operator<<(i32);
  33. Encoder& operator<<(i64);
  34. Encoder& operator<<(float);
  35. Encoder& operator<<(double);
  36. Encoder& operator<<(char const*);
  37. Encoder& operator<<(StringView);
  38. Encoder& operator<<(String const&);
  39. Encoder& operator<<(ByteBuffer const&);
  40. Encoder& operator<<(URL const&);
  41. Encoder& operator<<(Dictionary const&);
  42. Encoder& operator<<(File const&);
  43. template<typename K, typename V>
  44. Encoder& operator<<(HashMap<K, V> const& hashmap)
  45. {
  46. *this << (u32)hashmap.size();
  47. for (auto it : hashmap) {
  48. *this << it.key;
  49. *this << it.value;
  50. }
  51. return *this;
  52. }
  53. template<typename T>
  54. Encoder& operator<<(Vector<T> const& vector)
  55. {
  56. *this << (u64)vector.size();
  57. for (auto& value : vector)
  58. *this << value;
  59. return *this;
  60. }
  61. template<Enum T>
  62. Encoder& operator<<(T const& enum_value)
  63. {
  64. *this << AK::to_underlying(enum_value);
  65. return *this;
  66. }
  67. template<typename T>
  68. Encoder& operator<<(T const& value)
  69. {
  70. encode(value);
  71. return *this;
  72. }
  73. template<typename T>
  74. Encoder& operator<<(Optional<T> const& optional)
  75. {
  76. *this << optional.has_value();
  77. if (optional.has_value())
  78. *this << optional.value();
  79. return *this;
  80. }
  81. template<typename T>
  82. void encode(T const& value)
  83. {
  84. IPC::encode(*this, value);
  85. }
  86. private:
  87. void encode_u32(u32);
  88. void encode_u64(u64);
  89. MessageBuffer& m_buffer;
  90. };
  91. }