Decoder.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. /*
  2. * Copyright (c) 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/Forward.h>
  9. #include <AK/NumericLimits.h>
  10. #include <AK/StdLibExtras.h>
  11. #include <AK/String.h>
  12. #include <LibIPC/Forward.h>
  13. #include <LibIPC/Message.h>
  14. namespace IPC {
  15. template<typename T>
  16. inline bool decode(Decoder&, T&)
  17. {
  18. static_assert(DependentFalse<T>, "Base IPC::decoder() instantiated");
  19. VERIFY_NOT_REACHED();
  20. }
  21. class Decoder {
  22. public:
  23. Decoder(InputMemoryStream& stream, int sockfd)
  24. : m_stream(stream)
  25. , m_sockfd(sockfd)
  26. {
  27. }
  28. bool decode(bool&);
  29. bool decode(u8&);
  30. bool decode(u16&);
  31. bool decode(u32&);
  32. bool decode(u64&);
  33. bool decode(i8&);
  34. bool decode(i16&);
  35. bool decode(i32&);
  36. bool decode(i64&);
  37. bool decode(float&);
  38. bool decode(double&);
  39. bool decode(String&);
  40. bool decode(ByteBuffer&);
  41. bool decode(URL&);
  42. bool decode(Dictionary&);
  43. bool decode(File&);
  44. template<typename K, typename V>
  45. bool decode(HashMap<K, V>& hashmap)
  46. {
  47. u32 size;
  48. if (!decode(size) || size > NumericLimits<i32>::max())
  49. return false;
  50. for (size_t i = 0; i < size; ++i) {
  51. K key;
  52. if (!decode(key))
  53. return false;
  54. V value;
  55. if (!decode(value))
  56. return false;
  57. hashmap.set(move(key), move(value));
  58. }
  59. return true;
  60. }
  61. template<Enum T>
  62. bool decode(T& enum_value)
  63. {
  64. UnderlyingType<T> inner_value;
  65. if (!decode(inner_value))
  66. return false;
  67. enum_value = T(inner_value);
  68. return true;
  69. }
  70. template<typename T>
  71. bool decode(T& value)
  72. {
  73. return IPC::decode(*this, value);
  74. }
  75. template<typename T>
  76. bool decode(Vector<T>& vector)
  77. {
  78. u64 size;
  79. if (!decode(size) || size > NumericLimits<i32>::max())
  80. return false;
  81. for (size_t i = 0; i < size; ++i) {
  82. T value;
  83. if (!decode(value))
  84. return false;
  85. vector.append(move(value));
  86. }
  87. return true;
  88. }
  89. template<typename T>
  90. bool decode(Optional<T>& optional)
  91. {
  92. bool has_value;
  93. if (!decode(has_value))
  94. return false;
  95. if (!has_value) {
  96. optional = {};
  97. return true;
  98. }
  99. T value;
  100. if (!decode(value))
  101. return false;
  102. optional = move(value);
  103. return true;
  104. }
  105. private:
  106. InputMemoryStream& m_stream;
  107. int m_sockfd { -1 };
  108. };
  109. }