Add overload for as_bytes taking a single object

This commit is contained in:
MikeGitb 2016-11-19 03:15:37 +01:00
parent 9d13cb14c3
commit 8def2618cb
2 changed files with 54 additions and 0 deletions

View File

@ -670,6 +670,19 @@ span<typename Ptr::element_type>
make_span(Ptr& cont) make_span(Ptr& cont)
{ return span<typename Ptr::element_type>(cont); } { return span<typename Ptr::element_type>(cont); }
template <class T, class = std::enable_if_t<std::is_pod<T>::value>>
span<const byte, sizeof(T)>
as_bytes(const T& e) noexcept
{
return{ reinterpret_cast<const byte*>(&e),sizeof(T) };
}
template <class T, class = std::enable_if_t<std::is_trivially_copyable<T>::value>>
span<byte, sizeof(T)>
as_writeable_bytes(T& e) noexcept
{
return{ reinterpret_cast<byte*>(&e),sizeof(T) };
}
// Specialization of gsl::at for span // Specialization of gsl::at for span
template <class ElementType, std::ptrdiff_t Extent> template <class ElementType, std::ptrdiff_t Extent>

View File

@ -1444,6 +1444,47 @@ SUITE(span_tests)
} }
} }
struct MyTriviallyCopyableType {
MyTriviallyCopyableType(int i) :a(i), b(static_cast<char>(i)), c(i) {}
int a;
char b;
double c;
friend bool operator==(MyTriviallyCopyableType& l, MyTriviallyCopyableType& r) { return l.a == r.a && l.b == r.b && l.c == r.c; }
};
TEST(pod_as_bytes)
{
{
double src{ 10.5 };
double dst{};
auto src_b = as_bytes(src);
auto dst_b = as_writeable_bytes(dst);
std::copy(src_b.begin(), src_b.end(), dst_b.begin());
CHECK(std::equal(src_b.begin(), src_b.end(), dst_b.begin()));
CHECK(src == dst);
}
{
std::array<int, 10> src{ 1,2,3,4,5,6,7,8,9,10 };
std::array<int, 10> dst{};
auto src_b = as_bytes(src);
auto dst_b = as_writeable_bytes(dst);
std::copy(src_b.begin(), src_b.end(), dst_b.begin());
CHECK(std::equal(src_b.begin(), src_b.end(), dst_b.begin()));
CHECK(src == dst);
}
#ifdef CONFIRM_COMPILATION_ERRORS
{
MyTC_t src{ 5 };
MyTC_t dst{ 1 };
auto src_b = as_bytes(src);
auto dst_b = as_writeable_bytes(dst);
std::copy(src_b.begin(), src_b.end(), dst_b.begin());
CHECK(std::equal(src_b.begin(), src_b.end(), dst_b.begin()));
CHECK(src == dst);
}
#endif
}
TEST(fixed_size_conversions) TEST(fixed_size_conversions)
{ {
int arr[] = {1, 2, 3, 4}; int arr[] = {1, 2, 3, 4};