It’s actually pretty trivial to write a one-shot std::streambuf
that uses the buffer in place as the default behaviour of all the virtual functions of std::streambuf
does ‘the right thing’. You can just setg
the read area in construction and underflow
and uflow
can safely be left to return traits_type::eof()
as the end of the initial get area is the end of the stream.
e.g.:
#include <streambuf>
#include <iostream>
#include <istream>
#include <ostream>
struct OneShotReadBuf : public std::streambuf
{
OneShotReadBuf(char* s, std::size_t n)
{
setg(s, s, s + n);
}
};
char hw[] = "Hello, World!\n";
int main()
{
// In this case disregard the null terminator
OneShotReadBuf osrb(hw, sizeof hw - 1);
std::istream istr(&osrb);
istr >> std::cout.rdbuf();
}