Skip to content

Commit 52970ae

Browse files
committed
🐛 Fix sized issue with indivisible sizes
Problem: - `sized` does not work correctly when the sizes of `T` and `U` are not multiples, for example when computing the number of 4-byte values required to hold N 3-byte values. Solution: - Fix it.
1 parent 37cc9c5 commit 52970ae

2 files changed

Lines changed: 13 additions & 1 deletion

File tree

include/stdx/utility.hpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ template <typename T, typename U>
116116
if constexpr (sizeof(T) == sizeof(U)) {
117117
return sz;
118118
} else if constexpr (sizeof(T) > sizeof(U)) {
119-
return sz * (sizeof(T) / sizeof(U));
119+
return (sz * sizeof(T) / sizeof(U)) + (sizeof(T) % sizeof(U) & 1u);
120120
} else {
121121
return (sz * sizeof(T) + sizeof(U) - 1) / sizeof(U);
122122
}

test/utility.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,18 @@ TEST_CASE("sized<T> aliases", "[utility]") {
130130
static_assert(stdx::sized64{1}.in<std::uint64_t>() == 1);
131131
}
132132

133+
TEST_CASE("sized<T> in (downsize not divisible)", "[utility]") {
134+
using T = std::array<char, 3>;
135+
static_assert(sizeof(T) == 3);
136+
static_assert(stdx::sized<std::uint32_t>{2}.in<T>() == 3);
137+
}
138+
139+
TEST_CASE("sized<T> in (upsize not divisible)", "[utility]") {
140+
using T = std::array<char, 3>;
141+
static_assert(sizeof(T) == 3);
142+
static_assert(stdx::sized<T>{3}.in<std::uint32_t>() == 3);
143+
}
144+
133145
TEST_CASE("CX_VALUE structural value", "[utility]") {
134146
auto x = CX_VALUE(42);
135147
static_assert(x() == 42);

0 commit comments

Comments
 (0)