【发布时间】:2015-11-10 21:44:49
【问题描述】:
我尝试创建过滤器,它首先从流中读取主体大小,然后仅从流中消耗 body_size 字节。尽管正确创建了输出流,但由于某种原因,从输入流中读取了所有数据。有没有办法纠正这种行为?
struct body_size_filter {
size_t body_size;
size_t bytes_read;
typedef char char_type;
typedef boost::iostreams::multichar_input_filter_tag category;
template<typename Source>
std::streamsize read(Source& src, char* s, std::streamsize n)
{
if (bytes_read >= body_size + 4)
{
return -1;
}
int c;
// read body size
while (bytes_read < 4 && (c = boost::iostreams::get(src)) != EOF && c != boost::iostreams::WOULD_BLOCK)
{
body_size = body_size | (static_cast<size_t>(c) << (24 - 8 * bytes_read));
bytes_read++;
}
if (bytes_read < 4)
{
return c;
}
char* first = s;
char* last = s + n;
while (bytes_read < body_size + 4 && first != last && (c = boost::iostreams::get(src)) != EOF && c != boost::iostreams::WOULD_BLOCK )
{
*first++ = c;
bytes_read++;
}
std::streamsize result = static_cast<std::streamsize>(first - s);
return result == 0 && c != boost::iostreams::WOULD_BLOCK ? -1 : result;
}
body_size_filter()
{
body_size = 0;
bytes_read = 0;
}
};
和用法
boost::iostreams::filtering_streambuf<boost::iostreams::input> in;
in.push(body_size_filter());
in.push(buf);
boost::asio::streambuf body_buf;
boost::iostreams::copy(in, body_buf); // after this call buf.size() == 0 - i was expecting some data to be left in buffer
【问题讨论】:
-
你从来没有展示过
buf是什么……所以你怎么能“期待buf.size() != 0”呢? -
可能不相关,但我认为
c != boost::iostreams::WOULD_BLOCK ? -1 : result;需要是c == boost::iostreams::WOULD_BLOCK ? -1 : result;