0
0
Fork 0
mirror of https://github.com/matrix-construct/construct synced 2024-06-09 05:29:00 +02:00

ircd::buffer: Add explicit checked convenience type casts.

This commit is contained in:
Jason Volk 2022-07-06 17:32:25 -07:00
parent edf0448243
commit c652e8172c
2 changed files with 35 additions and 0 deletions

View file

@ -17,6 +17,10 @@ struct ircd::buffer::const_buffer
// Definition for this is somewhere in the .cc files where boost is incl.
operator boost::asio::const_buffer() const noexcept;
template<class R,
bool safety = true>
explicit operator const R *() const noexcept(!safety);
// For boost::spirit conceptual compliance; illegal/noop
void insert(const char *const &, const char &);
@ -92,3 +96,17 @@ ircd::buffer::const_buffer::insert(const char *const &,
assert(0);
__builtin_unreachable();
}
template<class R,
bool safety>
inline ircd::buffer::const_buffer::operator
const R *()
const noexcept(!safety)
{
assert(sizeof(R) <= size(*this));
if constexpr(safety)
if(unlikely(sizeof(R) > size(*this)))
throw std::bad_cast{};
return reinterpret_cast<const R *>(data(*this));
}

View file

@ -21,6 +21,10 @@ struct ircd::buffer::mutable_buffer
/// Conversion offered for the analogous asio buffer.
operator boost::asio::mutable_buffer() const noexcept;
template<class R,
bool safety = true>
explicit operator R *() const noexcept(!safety);
/// Allows boost::spirit to append to the buffer; this means the size() of
/// this buffer becomes a consumption counter and the real size of the buffer
/// must be kept separately. This is the lowlevel basis for a stream buffer.
@ -86,3 +90,16 @@ ircd::buffer::mutable_buffer::insert(char *const &it,
++std::get<1>(*this);
}
template<class R,
bool safety>
inline ircd::buffer::mutable_buffer::operator
R *()
const noexcept(!safety)
{
assert(sizeof(R) <= size(*this));
if constexpr(safety)
if(unlikely(sizeof(R) > size(*this)))
throw std::bad_cast{};
return reinterpret_cast<const R *>(data(*this));
}