view: add a method to extract type cast bytes from a view

This commit is contained in:
Danny Robson 2018-07-30 14:03:02 +10:00
parent ab495bb0f7
commit 2c47a3654d

View File

@ -588,6 +588,36 @@ namespace util {
}
///////////////////////////////////////////////////////////////////////////
/// extract a reference to a known type at the front of a byte-view
///
/// returns a reference to a value of the designated type at the front of
/// the byte-view, or throws an exception if there is insufficient data.
///
/// there are no validity or other checks performed on the returned data
/// (other than memory safety wrt to the view). this is deliberate, so
/// that the function is safe to call on user supplied data during
/// parsing routines. it is up to the user to ensure the object is valid.
///
/// the buffer object is advanced in place so that it no longer covers
/// the extract value
template <
typename ValueT,
typename ByteT,
typename = std::enable_if_t<sizeof (ByteT) == 1>
>
ValueT const&
extract (util::view<const ByteT*> &buffer)
{
if (buffer.size () < sizeof (ValueT))
throw std::runtime_error ("insufficient data for view shift");
ValueT const &res = *reinterpret_cast<ValueT const*> (buffer.data ());
buffer = buffer.consume (sizeof (ValueT));
return res;
}
///////////////////////////////////////////////////////////////////////////
template <
typename BeginA, typename EndA,