I am using boost::asio::async_read_until
to read the \\n
-ended line from the TCP socket. Let me please recall that async_read_until
signature is the following:
void-or-deduced async_read_until(
AsyncReadStream & s,
boost::asio::basic_streambuf< Allocator > & b,
char delim,
ReadHandler handler);
Here
boost::asio::streambuf b;
is auto resized object to store received data.
As far as I understand, it internally consists of buffer sequence, a list of boost::asio buffers. However, there is no easy way to obtain ForwardIterator to iterate over this internal buffer that consists of multiple contiguous regions.
I find the following usage pattern:
std::istream stream(&b);
std::istream_iterator<char> end;
std::istream_iterator<char> begin(stream);
However, here end
and begin
are InputIterators.
At the same time, boost::spirit::phrase_parse(begin, end, grammar, space, obj)
parser that could be used to parse obtained from socked line requires begin
and end
be ForwardIterators:
http://www.boost.org/doc/libs/1_63_0/libs/spirit/doc/html/spirit/support/multi_pass.html
This is required for backtracking. However, the data are actually already stored in the memory buffer in boost::asio::streambuf b
object, nothing prevents iterator from being dereferenced more than once.
Boost has buffers_begin()
and buffers_end()
which you can use on streambuf
's data()
:
#include <boost/asio.hpp>
#include <boost/spirit/include/qi.hpp>
namespace a = boost::asio;
namespace qi = boost::spirit::qi;
#include <iostream>
int main()
{
a::streambuf input;
std::ostream(&input) << "123, 4, 5; 78, 8, 9;\n888, 8, 8;";
auto f = a::buffers_begin(input.data()), l = a::buffers_end(input.data());
//std::copy(f, l, std::ostream_iterator<char>(std::cout));
std::vector<std::vector<int> > parsed;
bool ok = qi::phrase_parse(f, l, *(qi::int_ % ',' >> ';'), qi::space, parsed);
if (ok) {
std::cout << "parsed: \n";
for (auto& row : parsed) {
for (auto& v : row) { std::cout << v << " "; }
std::cout << ";\n";
}
}
else
std::cout << "parse failed\n";
if (f!=l)
std::cout << "remaining unparsed input: '" << std::string(f,l) << "'\n";
}
Prints (as expected):
parsed:
123 4 5 ;
78 8 9 ;
888 8 8 ;
Note don't forget to consume()
the parsed portion of the input!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.