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.
This commit is contained in:
AnotherTest 2020-11-07 23:09:45 +03:30 committed by Andreas Kling
parent 705ad670f3
commit c930e02624
Notes: sideshowbarker 2024-07-19 01:30:04 +09:00
4 changed files with 59 additions and 0 deletions

View file

@ -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;

View file

@ -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)

View file

@ -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();

View file

@ -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)