无缓冲 std Streambuf 实现

发布于 2024-11-30 00:20:19 字数 855 浏览 0 评论 0原文

为了对序列化库进行一些快速测试,我想创建一个可以从套接字读取/写入的streambuf。我不想在streambuf中使用缓冲区,而是让套接字处理这个问题。我确信序列化库只会调用 std::istream::read 和 std::ostream::write 。快速浏览一下 Microsoft 的 basic_streambuf 实现就会发现,这些调用实际上直接转发到 xsputnxsgetn

问题是:我可以从streambuf派生并仅实现xsputn和xsgetn,并确保使用我的实现的流将始终调用这些方法,而不是sync/overflow/underflow/pback/...?或者我应该覆盖同步等以返回错误,或者标准是否保证默认实现没问题?最好这应该在任何通用平台上工作,并且我不能使用 boost::iostreams。

实际上我会使用这样的东西:

class socket_buf : public std::streambuf
{
public:
    //Socket is a class with std::stream-like read/write methods
  MyBuf( Socket& s ) : sock( s ) {}

protected:
  std::streamsize xsputn( const char* s, std::streamsize n )
  {
    return sock.write( s, n );
  }

  std::streamsize xsgetn( char* s, std::streamsize n )
  {
    return sock.read( s, n );
  }

private:
  Socket& sock;
};

for some quick testing of a serialization library I want to create a streambuf that can read/write to/from a socket. I do not want to use a buffer in the streambuf, but let the socket handle this. I am sure the serialization lib will only call std::istream::read and std::ostream::write. A quick look at Microsoft's basic_streambuf implementation shows that these calls are practically directly forwarded to xsputn and xsgetn.

The question is: can I derive from a streambuf and just implement xsputn and xsgetn, and be sure that the streams that use my implementation will always call these methods, and not sync/overflow/underflow/pback/... ? Or else should I override sync etc to return errors, or does the standard guarantee that the default implementations are fine? Preferrably this should work on any common platform, and I cannot use the boost::iostreams.

Practically I'd use something like this:

class socket_buf : public std::streambuf
{
public:
    //Socket is a class with std::stream-like read/write methods
  MyBuf( Socket& s ) : sock( s ) {}

protected:
  std::streamsize xsputn( const char* s, std::streamsize n )
  {
    return sock.write( s, n );
  }

  std::streamsize xsgetn( char* s, std::streamsize n )
  {
    return sock.read( s, n );
  }

private:
  Socket& sock;
};

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小镇女孩 2024-12-07 00:20:19

如果没有缓冲区,(几乎?)不可能实现 std::streambuf。您必须重载 underflowoverflow,因为 std::streambuf 的许多公共接口不会通过 xsputn< /code> 或 xsgetn。例如sputcsbumpc等。甚至sputn也不能保证引起调用xsputn,具体取决于xsputn的状态内部缓冲区和特定的 std::streambuf 实现。

It's (almost?) impossible to implement a std::streambuf without a buffer. You will have to overload underflow and overflow as many of the public interfaces to std::streambuf won't go via xsputn or xsgetn. E.g. sputc, sbumpc, etc. Even sputn is not guaranteed to cause a call xsputn depending on the state of the internal buffer and the particular std::streambuf implementation.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文