Home  >  Article  >  Backend Development  >  How can I create an input stream from immutable memory?

How can I create an input stream from immutable memory?

Susan Sarandon
Susan SarandonOriginal
2024-11-09 04:47:01520browse

How can I create an input stream from immutable memory?

Constructing an Input Stream from Immutable Memory

In software development, it's often necessary to read data from memory buffers without copying or altering their contents. One such scenario is when the data is stored in a constant character pointer (const char*). To enable convenient reading from such buffers, creating an input stream is a viable solution.

A custom stream buffer can facilitate the creation of an input stream from immutable memory. Here's how to implement it:

#include <streambuf>
#include <istream>

struct membuf : std::streambuf {
    membuf(char const* base, size_t size) {
        char* p(const_cast<char*&>(base));
        this->setg(p, p, p + size);
    }
};

struct imemstream : virtual membuf, std::istream {
    imemstream(char const* base, size_t size)
        : membuf(base, size), std::istream(static_cast<std::streambuf*&>(this)) {
    }
};

The const_cast&> () in the stream buffer is necessary because the stream buffer is not modifying the data, but the interface requires a char.

Once the stream buffer is created, you can use it to initialize an input stream and read data from the buffer:

imemstream in(data, size);
int x;
float y;
std::string w;
in >> x >> y >> w;

The above is the detailed content of How can I create an input stream from immutable memory?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn