fix(streambuf): Buffer size

This commit is contained in:
Michael Carlberg 2017-01-14 09:42:46 +01:00
parent dceb3606b1
commit 6250a2b746
2 changed files with 9 additions and 7 deletions

View File

@ -56,7 +56,7 @@ class fd_streambuf : public std::streambuf {
template <typename... Args> template <typename... Args>
explicit fd_streambuf(Args&&... args) : m_fd(forward<Args>(args)...) { explicit fd_streambuf(Args&&... args) : m_fd(forward<Args>(args)...) {
setg(m_in, m_in, m_in); setg(m_in, m_in, m_in);
setp(m_out, m_out + sizeof(m_in)); setp(m_out, m_out + bufsize - 1);
} }
~fd_streambuf(); ~fd_streambuf();
@ -73,8 +73,9 @@ class fd_streambuf : public std::streambuf {
private: private:
file_descriptor m_fd; file_descriptor m_fd;
char m_out[BUFSIZ]{}; enum { bufsize = 1024 };
char m_in[BUFSIZ - 1]{}; char m_out[bufsize];
char m_in[bufsize - 1];
}; };
template <typename StreamType> template <typename StreamType>

View File

@ -2,6 +2,7 @@
#include <glob.h> #include <glob.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <cstdio> #include <cstdio>
#include <cstdlib>
#include <fstream> #include <fstream>
#include <streambuf> #include <streambuf>
@ -118,7 +119,7 @@ void fd_streambuf::open(int fd) {
} }
m_fd = fd; m_fd = fd;
setg(m_in, m_in, m_in); setg(m_in, m_in, m_in);
setp(m_out, m_out + sizeof(m_in)); setp(m_out, m_out + bufsize - 1);
} }
void fd_streambuf::close() { void fd_streambuf::close() {
@ -131,7 +132,7 @@ void fd_streambuf::close() {
int fd_streambuf::sync() { int fd_streambuf::sync() {
if (pbase() != pptr()) { if (pbase() != pptr()) {
auto size = pptr() - pbase(); auto size = pptr() - pbase();
auto bytes = ::write(m_fd, m_out, size); auto bytes = write(m_fd, m_out, size);
if (bytes > 0) { if (bytes > 0) {
std::copy(pbase() + bytes, pptr(), pbase()); std::copy(pbase() + bytes, pptr(), pbase());
setp(pbase(), epptr()); setp(pbase(), epptr());
@ -151,9 +152,9 @@ int fd_streambuf::overflow(int c) {
int fd_streambuf::underflow() { int fd_streambuf::underflow() {
if (gptr() == egptr()) { if (gptr() == egptr()) {
std::streamsize pback(std::min(gptr() - eback(), std::ptrdiff_t(m_in))); std::streamsize pback(std::min(gptr() - eback(), std::ptrdiff_t(16 - sizeof(int))));
std::copy(egptr() - pback, egptr(), eback()); std::copy(egptr() - pback, egptr(), eback());
int bytes(::read(m_fd, eback() + pback, BUFSIZ)); int bytes(read(m_fd, eback() + pback, bufsize));
setg(eback(), eback() + pback, eback() + pback + std::max(0, bytes)); setg(eback(), eback() + pback, eback() + pback + std::max(0, bytes));
} }
return gptr() == egptr() ? traits_type::eof() : traits_type::to_int_type(*gptr()); return gptr() == egptr() ? traits_type::eof() : traits_type::to_int_type(*gptr());