2

While working on a network library I recently noticed that having a pendant to basic_streambuf::in_avail in conjunction with a writesome function would be pretty handy for asynchronous I/O.

I have searched the web and checked several C++ references if there is any function which meets these demands, but it seems I had no luck. The only source which mentions similar functionality is Boost's Asio library, however the description clearly states that the function call will block until at least one byte has been sent which does not reflect my desired behaviour.

To elaborate on my question, I created a rough draft based on the C++ N3337 publication.

27.6.3.2.5 Put area [streambuf.pub.put]

streamsize in_depart();

Returns: If a write position is available, returns epptr() - pptr(). Otherwise returns showmanycp().

27.6.3.4.5 Put area [streambuf.virt.put]

streamsize showmanycp();

Returns: An estimate of the number of characters which can be written to the sequence, or -1. If it returns a positive value, then successive calls to overflow() will not return traits::eof() until at least that number of characters have been written to the stream. If showmanycp() returns -1, then calls to overflow()will fail.

Default behavior: Returns zero.

Remarks: Uses traits::eof().

27.7.3.7 Unformatted output functions [ostream.unformatted]

streamsize writesome(char_type* s, streamsize n);

Effects: Behaves as an unformatted output function (as described in 27.7.3.7, paragraph 1). After constructing a sentry object, if !good() callssetstate(failbit) which may throw an exception, and return. Otherwise writes n characters designated by s. If rdbuf()->in_depart() == -1, calls setstate(badbit) (which may throw ios_base::failure (27.5.5.4)), and writes no characters;

— If rdbuf()->in_depart() == 0, writes no characters.

— If rdbuf()->in_depart() > 0, writes min(rdbuf()->in_depart(), n)) characters.

Returns: The number of characters written.

4

1 回答 1

2

我猜你误解了in_avail()and的含义readsome():所有这些都说流已经读取了一个数据块并且缓冲区中仍然有字符。是的,理论上它可以做一些不同的事情,但特别是当从网络读取时,您不知道有多少数据可用,直到您尝试读取它。

同样,没有办法保证能够摆脱任何特定数量的字符:这out.writesome(buf, n)意味着什么?如果您希望它意味着您将n字符转储到out的缓冲区中,您可以创建一个合适的流缓冲区并使用write(). n但是,不能保证字节是通过阻塞发送的(至少对于1 < n)。不过,我猜你想要后者。

于 2012-09-17T12:40:06.933 回答