Encoder.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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<<(u32);
  28. Encoder& operator<<(u64);
  29. Encoder& operator<<(i8);
  30. Encoder& operator<<(i16);
  31. Encoder& operator<<(i32);
  32. Encoder& operator<<(i64);
  33. Encoder& operator<<(float);
  34. Encoder& operator<<(double);
  35. Encoder& operator<<(char const*);
  36. Encoder& operator<<(StringView const&);
  37. Encoder& operator<<(String const&);
  38. Encoder& operator<<(ByteBuffer const&);
  39. Encoder& operator<<(URL const&);
  40. Encoder& operator<<(Dictionary const&);
  41. Encoder& operator<<(File const&);
  42. template<typename K, typename V>
  43. Encoder& operator<<(HashMap<K, V> const& hashmap)
  44. {
  45. *this << (u32)hashmap.size();
  46. for (auto it : hashmap) {
  47. *this << it.key;
  48. *this << it.value;
  49. }
  50. return *this;
  51. }
  52. template<typename T>
  53. Encoder& operator<<(Vector<T> const& vector)
  54. {
  55. *this << (u64)vector.size();
  56. for (auto& value : vector)
  57. *this << value;
  58. return *this;
  59. }
  60. template<Enum T>
  61. Encoder& operator<<(T const& enum_value)
  62. {
  63. *this << AK::to_underlying(enum_value);
  64. return *this;
  65. }
  66. template<typename T>
  67. Encoder& operator<<(T const& value)
  68. {
  69. encode(value);
  70. return *this;
  71. }
  72. template<typename T>
  73. Encoder& operator<<(Optional<T> const& optional)
  74. {
  75. *this << optional.has_value();
  76. if (optional.has_value())
  77. *this << optional.value();
  78. return *this;
  79. }
  80. template<typename T>
  81. void encode(T const& value)
  82. {
  83. IPC::encode(*this, value);
  84. }
  85. private:
  86. MessageBuffer& m_buffer;
  87. };
  88. }