Browse Source

LibIPC: Add support for passing around ByteBuffers and HashMap<K, V>

It should be noted that using a shared buffer should still be preferred
over passing a raw ByteBuffer over the wire.
AnotherTest 4 years ago
parent
commit
c930e02624

+ 19 - 0
Libraries/LibIPC/Decoder.cpp

@@ -112,6 +112,25 @@ bool Decoder::decode(String& value)
     return !m_stream.handle_any_error();
 }
 
+bool Decoder::decode(ByteBuffer& value)
+{
+    i32 length = 0;
+    m_stream >> length;
+    if (m_stream.handle_any_error())
+        return false;
+    if (length < 0) {
+        value = {};
+        return true;
+    }
+    if (length == 0) {
+        value = ByteBuffer::create_uninitialized(0);
+        return true;
+    }
+    value = ByteBuffer::create_uninitialized(length);
+    m_stream >> value.bytes();
+    return !m_stream.handle_any_error();
+}
+
 bool Decoder::decode(URL& value)
 {
     String string;

+ 21 - 0
Libraries/LibIPC/Decoder.h

@@ -60,8 +60,29 @@ public:
     bool decode(i64&);
     bool decode(float&);
     bool decode(String&);
+    bool decode(ByteBuffer&);
     bool decode(URL&);
     bool decode(Dictionary&);
+    template<typename K, typename V>
+    bool decode(HashMap<K, V>& hashmap)
+    {
+        u32 size;
+        if (!decode(size) || size > NumericLimits<i32>::max())
+            return false;
+
+        for (size_t i = 0; i < size; ++i) {
+            K key;
+            if (!decode(key))
+                return false;
+
+            V value;
+            if (!decode(value))
+                return false;
+
+            hashmap.set(move(key), move(value));
+        }
+        return true;
+    }
 
     template<typename T>
     bool decode(T& value)

+ 8 - 0
Libraries/LibIPC/Encoder.cpp

@@ -24,6 +24,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+#include <AK/ByteBuffer.h>
 #include <AK/String.h>
 #include <AK/URL.h>
 #include <LibIPC/Dictionary.h>
@@ -141,6 +142,13 @@ Encoder& Encoder::operator<<(const String& value)
     return *this << value.view();
 }
 
+Encoder& Encoder::operator<<(const ByteBuffer& value)
+{
+    *this << static_cast<i32>(value.size());
+    m_buffer.append(value.data(), value.size());
+    return *this;
+}
+
 Encoder& Encoder::operator<<(const URL& value)
 {
     return *this << value.to_string();

+ 11 - 0
Libraries/LibIPC/Encoder.h

@@ -58,8 +58,19 @@ public:
     Encoder& operator<<(const char*);
     Encoder& operator<<(const StringView&);
     Encoder& operator<<(const String&);
+    Encoder& operator<<(const ByteBuffer&);
     Encoder& operator<<(const URL&);
     Encoder& operator<<(const Dictionary&);
+    template<typename K, typename V>
+    Encoder& operator<<(const HashMap<K, V>& hashmap)
+    {
+        *this << (u32)hashmap.size();
+        for (auto it : hashmap) {
+            *this << it.key;
+            *this << it.value;
+        }
+        return *this;
+    }
 
     template<typename T>
     Encoder& operator<<(const Vector<T>& vector)