From 7e6918e14abd11e919205b89bbe1e02876f0dea1 Mon Sep 17 00:00:00 2001 From: Andrew Kaster Date: Tue, 5 Mar 2024 09:12:18 -0700 Subject: [PATCH] LibIPC: Add support for encoding and decoding `Array` Also add a note to the Concepts header that the reason we have all the strange concepts in place for container types is to work around the language limitation that we cannot partially specialize function templates. --- Userland/Libraries/LibIPC/Concepts.h | 10 ++++++++++ Userland/Libraries/LibIPC/Decoder.h | 12 ++++++++++++ Userland/Libraries/LibIPC/Encoder.h | 11 +++++++++++ 3 files changed, 33 insertions(+) diff --git a/Userland/Libraries/LibIPC/Concepts.h b/Userland/Libraries/LibIPC/Concepts.h index 5afab8c923..6ddfb51f9a 100644 --- a/Userland/Libraries/LibIPC/Concepts.h +++ b/Userland/Libraries/LibIPC/Concepts.h @@ -21,6 +21,8 @@ // // Then decode() would be ambiguous because either declaration could work (the compiler would // not be able to distinguish if you wanted to decode an int or a Vector of int). +// +// They also serve to work around the inability to do partial function specialization in C++. namespace IPC::Concepts { namespace Detail { @@ -50,6 +52,11 @@ constexpr inline bool IsVector = false; template constexpr inline bool IsVector> = true; +template +constexpr inline bool IsArray = false; +template +constexpr inline bool IsArray> = true; + } template @@ -67,4 +74,7 @@ concept Variant = Detail::IsVariant; template concept Vector = Detail::IsVector; +template +concept Array = Detail::IsArray; + } diff --git a/Userland/Libraries/LibIPC/Decoder.h b/Userland/Libraries/LibIPC/Decoder.h index a3338b456d..108b43e2a0 100644 --- a/Userland/Libraries/LibIPC/Decoder.h +++ b/Userland/Libraries/LibIPC/Decoder.h @@ -108,6 +108,18 @@ ErrorOr decode(Decoder&); template<> ErrorOr decode(Decoder&); +template +ErrorOr decode(Decoder& decoder) +{ + T array {}; + auto size = TRY(decoder.decode_size()); + if (size != array.size()) + return Error::from_string_literal("Array size mismatch"); + for (size_t i = 0; i < array.size(); ++i) + array[i] = TRY(decoder.decode()); + return array; +} + template ErrorOr decode(Decoder& decoder) { diff --git a/Userland/Libraries/LibIPC/Encoder.h b/Userland/Libraries/LibIPC/Encoder.h index 508d5db348..075de49a82 100644 --- a/Userland/Libraries/LibIPC/Encoder.h +++ b/Userland/Libraries/LibIPC/Encoder.h @@ -108,6 +108,17 @@ ErrorOr encode(Encoder&, File const&); template<> ErrorOr encode(Encoder&, Empty const&); +template +ErrorOr encode(Encoder& encoder, Array const& array) +{ + TRY(encoder.encode_size(array.size())); + + for (auto const& value : array) + TRY(encoder.encode(value)); + + return {}; +} + template ErrorOr encode(Encoder& encoder, T const& vector) {