Trying to understand the boost::beast multibuffer

北慕城南 提交于 2019-12-05 21:24:29
Vinnie Falco

data() returns an object meeting the requirements of ConstBufferSequence (http://www.boost.org/doc/libs/1_65_0/doc/html/boost_asio/reference/ConstBufferSequence.html). prepare() returns an object meeting the requirements of MutableBufferSequence (http://www.boost.org/doc/libs/1_65_0/doc/html/boost_asio/reference/MutableBufferSequence.html)

All of the dynamic buffers in beast meet the requirements of DynamicBuffer, described in http://www.boost.org/doc/libs/develop/libs/beast/doc/html/beast/concepts/DynamicBuffer.html

If you want to convert a buffer sequence into a string you need to loop over each element and append it to the string individually. Such a function might look like this:

template<class ConstBufferSequence>
std::string
to_string(ConstBufferSequence const& buffers)
{
    std::string s;
    s.reserve(boost::asio::buffer_size(buffers));
    for(boost::asio::const_buffer b : buffers)
        s.append(boost::asio::buffer_cast<char const*>(b),
            boost::asio::buffer_size(b));
    return s;
}

Alternatively, if you want to avoid the buffer copy you can use something like beast::flat_buffer which guarantees that all the buffer sequences will have length one. Something like this:

inline
std::string
to_string(beast::flat_buffer const& buffer)
{
    return std::string(boost::asio::buffer_cast<char const*>(
        beast::buffers_front(buffer.data())),
            boost::asio::buffer_size(buffer.data()));
}

For more information on buffers, see http://www.boost.org/doc/libs/1_65_0/doc/html/boost_asio/overview/core/buffers.html

In the latest versions of Beast, there is now the function buffers_to_string which will do this for you in a single function call.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!