view: add extract_array

This commit is contained in:
Danny Robson 2021-11-12 13:49:40 +10:00
parent bdcb5c03c7
commit 37b48341bb

View File

@ -770,6 +770,37 @@ namespace cruft {
}
///------------------------------------------------------------------------
/// Returns a view of the specified type cast from the front of a
/// byte-view.
///
/// There may be runtime checks for alignment under debug builds.
///
/// It is safe to use this on untrusted input. However absolutely no
/// validation is performed on the result data.
template <
typename ValueT,
typename WordT,
typename = std::enable_if_t<sizeof (ValueT) % sizeof(WordT) == 0>
>
cruft::view<ValueT*>
extract_array (view<WordT*> &src, std::size_t count)
{
static_assert (
std::is_const_v<ValueT> == std::is_const_v<WordT>,
"src and dst types must have matching constness"
);
auto const src_size = sizeof (ValueT) / sizeof (WordT) * count;
if (unlikely (src.size () < src_size))
throw std::runtime_error ("Insufficient data for extraction");
auto res = src.template cast<ValueT*> ().redim (count);
src = src.consume (src_size);
return res;
}
///////////////////////////////////////////////////////////////////////////
/// extracts an object of a specified type from the front of a byte-view.
///