Added fmt support for byte

This commit is contained in:
mutouyun 2025-01-07 17:37:58 +08:00 committed by 木头云
parent 7e7bfb8467
commit e7b6fcd79d
2 changed files with 35 additions and 0 deletions

View File

@ -11,6 +11,7 @@
#include "libipc/imp/detect_plat.h" #include "libipc/imp/detect_plat.h"
#include "libipc/imp/span.h" #include "libipc/imp/span.h"
#include "libipc/imp/fmt.h"
#if defined(LIBIPC_CPP_17) && defined(__cpp_lib_byte) #if defined(LIBIPC_CPP_17) && defined(__cpp_lib_byte)
#define LIBIPC_CPP_LIB_BYTE_ #define LIBIPC_CPP_LIB_BYTE_
@ -160,4 +161,18 @@ auto as_bytes(span<T> s) noexcept -> span<Byte> {
return {byte_cast(s.data()), s.size_bytes()}; return {byte_cast(s.data()), s.size_bytes()};
} }
/// \brief Custom defined fmt_to method for imp::fmt
namespace detail_tag_invoke {
inline bool tag_invoke(decltype(ipc::fmt_to), fmt_context &ctx, ipc::byte b) {
return ipc::to_string(ctx, static_cast<std::uint8_t>(b), "02x");
}
template <typename T,
typename = std::enable_if_t<std::is_same<std::decay_t<T>, ipc::byte>::value>>
bool tag_invoke(decltype(ipc::fmt_to), fmt_context &ctx, fmt_ref<T> arg) noexcept {
return ipc::to_string(ctx, static_cast<std::uint8_t>(arg.param), arg.fstr);
}
} // namespace detail_tag_invoke
} // namespace ipc } // namespace ipc

View File

@ -6,6 +6,8 @@
#include "test.h" #include "test.h"
#include "libipc/imp/fmt.h" #include "libipc/imp/fmt.h"
#include "libipc/imp/byte.h"
#include "libipc/imp/span.h"
TEST(fmt, spec) { TEST(fmt, spec) {
EXPECT_STREQ(ipc::spec("hello")(123).fstr.data(), "hello"); EXPECT_STREQ(ipc::spec("hello")(123).fstr.data(), "hello");
@ -123,3 +125,21 @@ bool tag_invoke(decltype(ipc::fmt_to), ipc::fmt_context &, foo arg) noexcept(fal
TEST(fmt, throw) { TEST(fmt, throw) {
EXPECT_THROW(std::ignore = ipc::fmt(foo{}), foo); EXPECT_THROW(std::ignore = ipc::fmt(foo{}), foo);
} }
TEST(fmt, byte) {
{
ipc::byte b1{}, b2(31);
EXPECT_EQ(ipc::fmt(b1), "00");
EXPECT_EQ(ipc::fmt(b2), "1f");
EXPECT_EQ(ipc::fmt(ipc::spec("03X")(b2)), "01F");
}
{
ipc::byte bs[] {31, 32, 33, 34, 35, 36, 37, 38};
EXPECT_EQ(ipc::fmt(ipc::make_span(bs)), "1f 20 21 22 23 24 25 26");
}
}
TEST(fmt, span) {
EXPECT_EQ(ipc::fmt(ipc::span<int>{}), "");
EXPECT_EQ(ipc::fmt(ipc::make_span({1, 3, 2, 4, 5, 6, 7})), "1 3 2 4 5 6 7");
}