Copy a streambuf's contents to a string

前端 未结 10 1973
时光取名叫无心
时光取名叫无心 2020-11-29 22:19

Apparently boost::asio::async_read doesn\'t like strings, as the only overload of boost::asio::buffer allows me to create const_buffer

相关标签:
10条回答
  • 2020-11-29 23:12

    Another possibility with boost::asio::streambuf is to use boost::asio::buffer_cast<const char*>() in conjunction with boost::asio::streambuf::data() and boost::asio::streambuf::consume() like this:

    const char* header=boost::asio::buffer_cast<const char*>(readbuffer.data());
    //Do stuff with header, maybe construct a std::string with std::string(header,header+length)
    readbuffer.consume(length);
    

    This won't work with normal streambufs and might be considered dirty, but it seems to be the fastest way of doing it.

    0 讨论(0)
  • 2020-11-29 23:13

    It's really buried in the docs...

    Given boost::asio::streambuf b, with size_t buf_size ...

    boost::asio::streambuf::const_buffers_type bufs = b.data();
    std::string str(boost::asio::buffers_begin(bufs),
                    boost::asio::buffers_begin(bufs) + buf_size);
    
    0 讨论(0)
  • 2020-11-29 23:13

    A simpler answer would be to convert it in std::string and manipulate it some what like this

     std::string buffer_to_string(const boost::asio::streambuf &buffer)
     {
      using boost::asio::buffers_begin;
      auto bufs = buffer.data();
      std::string result(buffers_begin(bufs), buffers_begin(bufs) + buffer.size());
     return result;
    }
    

    Giving a very concise code for the task.

    0 讨论(0)
  • 2020-11-29 23:14

    I think it's more like:

    
    streambuf.commit( number_of_bytes_read );
    
    istream istr( &streambuf );
    string s;
    istr >> s;
    

    I haven't looked into the basic_streambuf code, but I believe that should be just one copy into the string.

    0 讨论(0)
提交回复
热议问题