feat: add support for string_view as D-Bus type

This commit is contained in:
Stanislav Angelovič
2024-04-16 18:07:47 +02:00
parent d856969051
commit f15c260750
5 changed files with 39 additions and 3 deletions

View File

@@ -100,6 +100,7 @@ namespace sdbus {
Message& operator<<(double item);
Message& operator<<(const char *item);
Message& operator<<(const std::string &item);
Message& operator<<(std::string_view item);
Message& operator<<(const Variant &item);
template <typename ...Elements>
Message& operator<<(const std::variant<Elements...>& value);

View File

@@ -41,6 +41,7 @@
# endif
#endif
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <unordered_map>
@@ -231,6 +232,10 @@ namespace sdbus {
static constexpr bool is_trivial_dbus_type = false;
};
template <>
struct signature_of<std::string_view> : signature_of<std::string>
{};
template <>
struct signature_of<char*> : signature_of<std::string>
{};

View File

@@ -35,6 +35,7 @@
#include "ScopeGuard.h"
#include <cassert>
#include <cstring>
#include SDBUS_HEADER
namespace sdbus {
@@ -197,6 +198,17 @@ Message& Message::operator<<(const std::string& item)
return *this;
}
Message& Message::operator<<(std::string_view item)
{
char* destPtr{};
auto r = sd_bus_message_append_string_space((sd_bus_message*)msg_, item.length(), &destPtr);
SDBUS_THROW_ERROR_IF(r < 0, "Failed to serialize a string_view value", -r);
std::memcpy(destPtr, item.data(), item.length());
return *this;
}
Message& Message::operator<<(const Variant &item)
{
item.serializeTo(*this);

View File

@@ -204,6 +204,21 @@ TEST(AMessage, CanCarryASimpleInteger)
ASSERT_THAT(dataRead, Eq(dataWritten));
}
TEST(AMessage, CanCarryAStringAsAStringView)
{
auto msg = sdbus::createPlainMessage();
const std::string_view dataWritten = "Hello";
msg << dataWritten;
msg.seal();
std::string dataRead;
msg >> dataRead;
ASSERT_THAT(dataRead, Eq(dataWritten));
}
TEST(AMessage, CanCarryAUnixFd)
{
auto msg = sdbus::createPlainMessage();

View File

@@ -85,6 +85,7 @@ namespace
TYPE(double)HAS_DBUS_TYPE_SIGNATURE("d")
TYPE(const char*)HAS_DBUS_TYPE_SIGNATURE("s")
TYPE(std::string)HAS_DBUS_TYPE_SIGNATURE("s")
TYPE(std::string_view)HAS_DBUS_TYPE_SIGNATURE("s")
TYPE(sdbus::BusName)HAS_DBUS_TYPE_SIGNATURE("s")
TYPE(sdbus::InterfaceName)HAS_DBUS_TYPE_SIGNATURE("s")
TYPE(sdbus::MemberName)HAS_DBUS_TYPE_SIGNATURE("s")
@@ -122,10 +123,11 @@ namespace
>,
sdbus::Signature,
sdbus::UnixFd,
const char*
const char*,
std::string_view
>
>;
TYPE(ComplexType)HAS_DBUS_TYPE_SIGNATURE("a{t(a{ya(oanbva{is})}ghs)}")
TYPE(ComplexType)HAS_DBUS_TYPE_SIGNATURE("a{t(a{ya(oanbva{is})}ghss)}")
typedef ::testing::Types< bool
, uint8_t
@@ -138,6 +140,7 @@ namespace
, double
, const char*
, std::string
, std::string_view
, sdbus::BusName
, sdbus::InterfaceName
, sdbus::MemberName