feat(span): Add 'as_bytes' and 'as_writable_bytes' (#689)

These functions emulates the std C++20 functions std::as_bytes and
std::as_writable_bytes.
This commit is contained in:
devjoa 2023-05-02 00:39:55 +02:00 committed by GitHub
parent 8a46297486
commit 40c4fc7c10
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 44 additions and 0 deletions

View File

@ -41,6 +41,7 @@ SOFTWARE.
#include "integral_limits.h"
#include "memory.h"
#include "array.h"
#include "byte.h"
#include "private/dynamic_extent.h"
@ -944,6 +945,24 @@ namespace etl
}
};
#endif
//*************************************************************************
/// Obtains a view to the object representation of the elements of the span s.
//*************************************************************************
template <class T, std::size_t N>
auto as_bytes(span<T, N> s) ETL_NOEXCEPT
{
return span <const byte, (N == etl::dynamic_extent) ? (etl::dynamic_extent) : (N * sizeof(T)) > {reinterpret_cast<byte*>(s.data()), s.size_bytes()};
}
template <class T, std::size_t N>
auto as_writable_bytes(span<T, N> s) ETL_NOEXCEPT
{
ETL_STATIC_ASSERT(not etl::is_const<T>::value, "span<T> must be of non-const type");
return span <byte, (N == etl::dynamic_extent) ? (etl::dynamic_extent) : (N * sizeof(T)) > {reinterpret_cast<byte*>(s.data()), s.size_bytes()};
}
}
#endif

View File

@ -1125,6 +1125,19 @@ namespace
CHECK_FALSE(view8 != view8);
}
//*************************************************************************
TEST(test_convert_span_any_to_span_byte)
{
/* mutable */ float data[2]{3.141592f, 2.71828f };
auto const const_bytes = etl::as_bytes(etl::span<float, etl::dynamic_extent>{data});
auto const writable_bytes = etl::as_writable_bytes(etl::span<float, etl::dynamic_extent>{data});
CHECK_TRUE(const_bytes.size() == sizeof(data));
CHECK_TRUE(writable_bytes.size() == sizeof(data));
}
#include "etl/private/diagnostic_pop.h"
};
}

View File

@ -1070,6 +1070,18 @@ namespace
CHECK_FALSE(view6 != view7);
}
TEST(test_convert_span_any_to_span_byte)
{
/* mutable */ float data[2]{3.141592f, 2.71828f};
auto const const_bytes = etl::as_bytes(etl::span{data});
auto const writable_bytes = etl::as_writable_bytes(etl::span{data});
CHECK_TRUE(const_bytes.size() == sizeof(data));
CHECK_TRUE(writable_bytes.size() == sizeof(data));
}
#include "etl/private/diagnostic_pop.h"
};
}