Decoder.h 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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(String&);
  39. bool decode(ByteBuffer&);
  40. bool decode(URL&);
  41. bool decode(Dictionary&);
  42. bool decode(File&);
  43. template<typename K, typename V>
  44. bool decode(HashMap<K, V>& hashmap)
  45. {
  46. u32 size;
  47. if (!decode(size) || size > NumericLimits<i32>::max())
  48. return false;
  49. for (size_t i = 0; i < size; ++i) {
  50. K key;
  51. if (!decode(key))
  52. return false;
  53. V value;
  54. if (!decode(value))
  55. return false;
  56. hashmap.set(move(key), move(value));
  57. }
  58. return true;
  59. }
  60. template<Enum T>
  61. bool decode(T& enum_value)
  62. {
  63. UnderlyingType<T> inner_value;
  64. if (!decode(inner_value))
  65. return false;
  66. enum_value = T(inner_value);
  67. return true;
  68. }
  69. template<typename T>
  70. bool decode(T& value)
  71. {
  72. return IPC::decode(*this, value);
  73. }
  74. template<typename T>
  75. bool decode(Vector<T>& vector)
  76. {
  77. u64 size;
  78. if (!decode(size) || size > NumericLimits<i32>::max())
  79. return false;
  80. for (size_t i = 0; i < size; ++i) {
  81. T value;
  82. if (!decode(value))
  83. return false;
  84. vector.append(move(value));
  85. }
  86. return true;
  87. }
  88. template<typename T>
  89. bool decode(Optional<T>& optional)
  90. {
  91. bool has_value;
  92. if (!decode(has_value))
  93. return false;
  94. if (!has_value) {
  95. optional = {};
  96. return true;
  97. }
  98. T value;
  99. if (!decode(value))
  100. return false;
  101. optional = move(value);
  102. return true;
  103. }
  104. private:
  105. InputMemoryStream& m_stream;
  106. int m_sockfd { -1 };
  107. };
  108. }