Search code examples
c++istreamseekstreambuf

How to implement custom std::streambuf's seekoff()?


I have the following implementation based on e.g. this question and answer

struct membuf : std::streambuf
{
  membuf(char* begin, char* end)
  {
    this->setg(begin, begin, end);
  }

protected:
  virtual pos_type seekoff(off_type off,
                           std::ios_base::seekdir dir,
                           std::ios_base::openmode which = std::ios_base::in)
  {
    std::istream::pos_type ret;
    if(dir == std::ios_base::cur)
    {
      this->gbump(off);
    }
    // something is missing here...
  }
};

I would like to use it in my methods in the following way:

  char buffer[] = { 0x01, 0x0a };
  membuf sbuf(buffer, buffer + sizeof(buffer));
  std::istream in(&sbuf);

and then call e.g. tellg() on in and get the correct result.

So far it's almost perfect - it doesn't stop at the end of the stream.

How should I upgrade this so that it works correctly?

My main motivation is to mimic std::ifstream behavior but with binary char[] fed into them in tests (instead of relying on binary files).


Solution

  • It seems that I was missing the return with current position. So the final implementation of seekoff looks like:

      pos_type seekoff(off_type off,
                       std::ios_base::seekdir dir,
                       std::ios_base::openmode which = std::ios_base::in)
      {
        if (dir == std::ios_base::cur) gbump(off);
    
        return gptr() - eback();
      }