Following from Get an istream from a char*, I'm trying to write a mock stream container for some tests which looks as follows:
struct mock_membuf : std::streambuf
{
mock_membuf(char* begin, char* end) {
this->setg(begin, begin, end);
}
};
struct MockStreamContainer{
explicit MockStreamContainer(char* buffer, int offset, int nbytes): m_sbuf(buffer + offset, buffer + offset + nbytes), m_body(&m_sbuf), m_size(nbytes) {}
std::istream& Body() const {
return m_body;
}
int Size() const {
return m_size;
}
mock_membuf m_sbuf; // same as membuf from the question referenced
std::istream& m_body;
int64_t m_size;
};
and will be used as follows:
int main()
{
char buffer[] = "I'm a buffer with embedded nulls\0and line\n feeds";
auto get_stream = [&buffer](int offset, int nbytes) {
return MockStreamContainer(buffer, offset, nbytes);
};
std::string line;
auto r = get_stream(5, 10);
std::istream& in = r.Body();
while (std::getline(in, line)) {
std::cout << "line: " << line << "\n";
}
return 0;
}
The above code is just something I tried(here is a link) and is error ridden - Any suggestions as to how this can be correctly and efficiently implemented?
P.S. As requested the above code throws the following compilation error currently:
main.cpp: In constructor 'MockStreamContainer::MockStreamContainer(char*, int, int)':
main.cpp:17:131: error: invalid initialization of non-const reference of type 'std::istream&' {aka 'std::basic_istream<char>&'} from an rvalue of type 'mock_membuf*'
explicit MockStreamContainer(char* buffer, int offset, int nbytes): m_sbuf(buffer + offset, buffer + offset + nbytes), m_body(&m_sbuf), m_size(nbytes) {}
Edit: Thanks to @Martin York's answer, I was able to fix the problem by making a minor change: convert m_body to a pointer instead of a reference.