views:

128

answers:

3

Hello! My problem can be described the following way:

I have some data which actually is an array and could be represented as char* data with some size

I also have some legacy code (function) that takes some abstract std::istream object as a param and uses that stream to retrieve data to operate.

So, my question is the following - what would be the easy way to map my data to some std::istream object so that I can pass it to my function? I thought about creating a std::stringstream object from my data, but that means copying and (as I assume) isn't the best solution.

Any ideas how this could be done so that my std::istream operates on the data directly?

Thank you.

+4  A: 

You can implement a derived std::streambuf class, and use it with an input stream.

Alex B
+6  A: 

If you're looking at actually creating your own stream, I'd look at the Boost.Iostreams library. It makes it easy to create your own stream objects.

rlbond
And, IIRC, already has the glue for pulling stuff out of a std::vector or an array.
Thanatos
+1  A: 

Use string stream:

#include <sstream>

int main()
{
    char[]  data = "PLOP PLOP PLOP";
    int     size = 13;  // PS I know this is not the same as strlen(data);

    std::stringstream  stream(std::string(data, size));

    // use stream as an istream;
}

If you want to be real effecient you can muck with the stream buffer directly. I have not tried this and do not have a compiler to test with, but the folowing should work:

#include <sstream>

int main()
{
    char[]  data = "PLOP PLOP PLOP";
    int     size = 13;  // PS I know this is not the same as strlen(data);

    std::stringstream  stream;
    stream.rdbuf()->pubsetbuf(data, size);

    // use stream as an istream;
}
Martin York