1

I have a buffer unsigned char *buffer filled with size bytes. I wanna init a stream from it.

I can do it as follow, which copys the buffer bytes:

string s(bytes, bytes + size);
stringstream ss(s);

I wonder if I can init a stream without that copy?

smilingpoplar
  • 1,065
  • 1
  • 15
  • 26

1 Answers1

3

You need to implement a custom streambuf that you then pass to the istream constructor. This will allow you to access the array data as any other stream. See the following links for more details:

  1. std::streambuf
  2. std::istream

Boost provides the iostreams library for helping with this. In particular, it already provides the array_source class for wrapping standard arrays. The following code sample illustrates how to accomplish this:

#include <cstdlib>
#include <iostream>
#include <string>

#include <boost/iostreams/stream_buffer.hpp>
#include <boost/iostreams/device/array.hpp>


namespace io = boost::iostreams;

int main(int argc, char* argv[]) {
    const char buffer[] = "buffer data\n";

    io::array_source src{ buffer, strlen(buffer) };
    io::stream_buffer<io::array_source> strbuf{ src };

    std::istream stream{ &strbuf };
    std::string line;
    std::getline(stream, line);
    std::cout << line << std::endl;
    return EXIT_SUCCESS;
}
TAS
  • 2,039
  • 12
  • 17
  • boost::iostreams [copies the data into a buffer](http://www.boost.org/doc/libs/1_55_0/libs/iostreams/doc/concepts/source.html) – Marco Kinski Nov 20 '13 at 14:27
  • @MarcoKinski Not sure how the link you posted gives this information. Could you provide more detail? – TAS Nov 21 '13 at 06:11
  • @TAS boost::iostreams::stream_buffer delegates the work to a "Device". "Source" is a "Device" for input purposes and this interface gives you no alternative as to copy the data into a buffer. – Marco Kinski Nov 25 '13 at 12:19