yhirose/cpp-httplib

DataSink outputstream fails handling single chars

stevem2t opened this issue · 0 comments

Hello,
please consider the following code:

#include <httplib.h>
using namespace httplib;

int main()
{
	auto provider = []( size_t /*off*/, DataSink& sink )->bool{
				auto& os = sink.os;
				os << "line 1\n";
				os << 'X';
				os << "DONE OK\n";
				sink.done();
				return true;
	};
	
	httplib::Server srv;
	srv.Get("/", [&](const httplib::Request &, httplib::Response &rsp) {
		rsp.set_content_provider( "text/html", provider );
	});
	srv.listen("0.0.0.0", 8080);
}

compile, run, and do a curl localhost:8080/
Expected:

line 1
X
DONE OK

But we get:

line 1

The explanation is easy:

  • The datasink streambuf only implements xsputn
  • it has no buffer set.
  • a single char write will call default streambuf::overflow(), which justs returns eof...
  • and the the stream eof/error is set and nothing more is emitted.

The minimum is probably just to implement overflow(), which, without buffer support, just needs to be like:

		int_type overflow( int_type ch ) override {
			if( ch != traits_type::eof() )
			{
				char cc = ch;
				if( 1 == xsputn( &cc, 1 ) )
					return ch; // or whatever not eof...
			}
			return traits_type::eof();
		  }

However for real usability, user buffer customization (via pubsetbuf) would be useful.
Please tell me if you want to go directly with a proper buffer support of if the interim simple version might be enough.
Best,

--
Steve