Encoder.h 2.2 KB

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