How can i create istream from uint8_t vector?

I am in the process of adding the ability to receive data over the network to code used only to read local files. The network library that I use sends and receives data in the form vector<uint8_t>. I would like to be able to reuse the code that processes the data after reading the file, but this code expects std :: istream, is there a way for istream to read vector data? This is the same data, so I feel that there must be a way, but I could not find or figure out the code to do this.

current code:

    std::ifstream stream("data.img", std::ios::in | std::ios::binary | std::ios::ate);

    if (!stream.is_open())
    {
        throw std::invalid_argument("Could not open file.");
    }
    // the arg for processData is std::istream
    processData(stream);

network structure:

    vector<uint8_t> data = networkMessage.data;

    // need some way to create istream from data
    std::istream stream = ?

    processData(stream);
    stream.close();

Is there a way to do this, or am I barking the wrong tree?

+9
source share
4 answers

, std::string std::istringstream, ( unsigned char to signed char):

std::string s((char*)networkMessage.data(),networkMessage.size());
std::istringstream iss(s);

std::istream& stream = iss;
         // ^ Note the reference here.

processData(stream);
stream.close();
0

std::basic_istream std::basic_streambuf. STL - - , / -.

( ) streambuf , std::vector , std::istream, streambuf. ( imemstream ):

std::vector<uint8_t> &data = networkMessage.data;
imemstream stream(reinterpret_cast<const char*>(data.data()), data.size());
processData(stream);
+1

, C++ - istrstream, :

    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);

, , . C++ 98 , , , .

0

, uint8_t:

template <class T>
auto make_istringstream_std_1(const std::vector<T>& v) -> std::istringstream
{
    using namespace std::string_literals;
    std::string str;

    for (auto& e : v)
    {
        str += std::to_string(e) + " "s;
    }
    // the trailing space is not an issue

    return std::istringstream{str};
}

std

template <class T>
auto make_istringstream_std_2(const std::vector<T>& v) -> std::istringstream
{
    std::stringstream ss;
    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " "));
    // the trailing space is not an issue

    return std::istringstream{ss.str()};
}

template <class T>
auto make_istringstream_boost(const std::vector<T>& v) -> std::istringstream
{
    using boost::adaptors::transformed;
    using boost::algorithm::join;

    return std::istringstream{
        join(v | transformed([](int a) { return std::to_string(a); }), " ")};
}

:

<int> ?

boost:: algorithm:: join

-1

All Articles