Skip to content

Commit

Permalink
[struct_pack] relax limitation for long (#535)
Browse files Browse the repository at this point in the history
  • Loading branch information
poor-circle authored Dec 21, 2023
1 parent 72238a5 commit 3ae41f7
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 12 deletions.
33 changes: 22 additions & 11 deletions include/ylt/struct_pack/type_id.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,28 @@ constexpr type_id get_integral_type() {
return type_id::uint128_t;
}
#endif
else if constexpr (std::is_same_v<long, T>) {
if constexpr (sizeof(long) == sizeof(int32_t)) {
return type_id::int32_t;
}
else if constexpr (sizeof(long) == sizeof(int64_t)) {
return type_id::int64_t;
}
else {
static_assert(!sizeof(T), "unsupport size of long type");
}
}
else if constexpr (std::is_same_v<unsigned long, T>) {
if constexpr (sizeof(unsigned long) == sizeof(uint32_t)) {
return type_id::uint32_t;
}
else if constexpr (sizeof(unsigned long) == sizeof(uint64_t)) {
return type_id::uint64_t;
}
else {
static_assert(!sizeof(T), "unsupport size of long type");
}
}
else {
/*
* Due to different data model,
Expand All @@ -219,17 +241,6 @@ constexpr type_id get_integral_type() {
!std::is_same_v<wchar_t, T>,
"Tips: Add macro STRUCT_PACK_ENABLE_UNPORTABLE_TYPE to support "
"wchar_t");
static_assert(!std::is_same_v<long, T> && !std::is_same_v<unsigned long, T>,
"The long types have different width in "
"different data model. "
"see "
"https://en.cppreference.com/w/cpp/language/"
"types. "
"Please use fixed width integer types. e.g. "
"int32_t, int64_t. "
"see "
"https://en.cppreference.com/w/cpp/types/"
"integer.");
static_assert(!sizeof(T), "not supported type");
// This branch will always compiled error.
}
Expand Down
36 changes: 35 additions & 1 deletion src/struct_pack/tests/test_data_struct2.cpp
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#include <climits>
#include <cstdint>
#include <ylt/struct_pack.hpp>

#include "doctest.h"
Expand Down Expand Up @@ -579,4 +581,36 @@ TEST_CASE("testing trivial_view type") {
CHECK(test_equal(result.value(), a_v3));
}
};
#endif
#endif

struct long_test {
long hi = -1;
unsigned long hi2 = ULONG_MAX;
};

struct long_test2 {
int64_t hi = -1;
uint64_t hi2 = UINT64_MAX;
};

struct long_test3 {
int32_t hi = -1;
uint32_t hi2 = UINT32_MAX;
};

TEST_CASE("testing long type") {
if constexpr (sizeof(long) == 8) {
auto buffer = struct_pack::serialize(long_test{});
auto result = struct_pack::deserialize<long_test2>(buffer);
CHECK(result.has_value());
CHECK(result->hi == -1);
CHECK(result->hi2 == ULONG_MAX);
}
else if constexpr (sizeof(long) == 4) {
auto buffer = struct_pack::serialize(long_test{});
auto result = struct_pack::deserialize<long_test3>(buffer);
CHECK(result.has_value());
CHECK(result->hi == -1);
CHECK(result->hi2 == ULONG_MAX);
}
}

0 comments on commit 3ae41f7

Please sign in to comment.