将 boost streambuf 转换为 string_ref
Converting boost streambuf to string_ref
以下代码对我来说编译得很好,但考虑到 ASIO 缓冲区的设计有些复杂,我不确定它是否正确。目的是允许将 streambuf
的内容提供给 HTTP 解析器,而无需创建中间 std::string
对象,这似乎是其他 ASIO 代码示例所做的。
boost::string_ref makeStringRef(const boost::asio::streambuf& streambuf)
{
auto&& bufferType = streambuf.data();
return {
boost::asio::buffer_cast<const char*>(bufferType),
boost::asio::buffer_size(bufferType)
};
}
我认为这确实是不正确的,因为 streambuf 可能有几个不连续的区域。
所以无论如何你都需要复制。或者,只需读入固定缓冲区即可。当然,这需要你提前知道最大尺寸,或者分几步阅读。
By the way, by taking a const&
you risk creating a string_ref
that refers to a temporary. Always try to be explicit about life time expectations.
以下代码对我来说编译得很好,但考虑到 ASIO 缓冲区的设计有些复杂,我不确定它是否正确。目的是允许将 streambuf
的内容提供给 HTTP 解析器,而无需创建中间 std::string
对象,这似乎是其他 ASIO 代码示例所做的。
boost::string_ref makeStringRef(const boost::asio::streambuf& streambuf)
{
auto&& bufferType = streambuf.data();
return {
boost::asio::buffer_cast<const char*>(bufferType),
boost::asio::buffer_size(bufferType)
};
}
我认为这确实是不正确的,因为 streambuf 可能有几个不连续的区域。
所以无论如何你都需要复制。或者,只需读入固定缓冲区即可。当然,这需要你提前知道最大尺寸,或者分几步阅读。
By the way, by taking a
const&
you risk creating astring_ref
that refers to a temporary. Always try to be explicit about life time expectations.