How can i create a istream from a uint8_t vector?
std::basic_istream
gets its data from an associated std::basic_streambuf
derived class. The STL provides such classes for file I/O and string I/O, but not for memory I/O or network I/O.
You could easily write (or find a 3rd party) memory-based streambuf
class that uses the std::vector
as its underlying buffer, and then you can construct an std::istream
that uses that memory streambuf
. For example (using the imemstream
class from
this answer):
std::vector<uint8_t> &data = networkMessage.data;
imemstream stream(reinterpret_cast<const char*>(data.data()), data.size());
processData(stream);
Well C++ does actually have a class for this - istrstream
, and you could use it like this:
vector<uint8_t> data = ...;
// need some way to create istream from data
std::istrstream stream(reinterpret_cast<const char*>(data.data()), data.size());
processData(stream);
As far as I can tell this doesn't copy the data, unlike the other answers. However it was also deprecated in C++98 because it's hard to know who is responsible for freeing the buffer, so you may want to write your own equivalent.