Adapting C++ std/boost iostreams to provide cyclic write to memory block -
background: i'm trying optimize logging system uses memory-mapped files. need provide std::ostream-like interface logging system can write memory. have identified std::strstream (which deprecated though) , boost::iostreams::basic_array_sink fit needs.
now want have logging cyclic, meaning when output pointer near end of memory block should start on @ beginning again. question best point start in order implement specific behaviour.
i'm rather overwhelmed std::iostreams class hierarchy , don't grasp internal workings now. i'm uncertain whether should/need derive ostream, streambuf, or both? these made being derived from, anyway?
or using boost:iostreams, need have write own sink?
edit: following attempt compiles , produces expected output:
class rollingstreambuf : public std::basic_streambuf<tchar> { public: typedef std::basic_streambuf<tchar> base; rollingstreambuf(base::char_type* baseptr, size_t size) { setp(baseptr, baseptr + size); } protected: virtual int_type overflow (int_type c) { // reset position start of buffer setp(pbase(), epptr()); return putchar(c); } virtual std::streamsize xsputn (const char* s, std::streamsize n) { if (n >= epptr() - pptr()) // reset position start of buffer setp(pbase(), epptr()); return base::xsputn(s, n); } }; char buffer[100]; rollingstreambuf buf(buffer, sizeof(buffer)); std::basic_ostream<tchar> out(&buf); (int i=0; i<10; i++) { out << "mumblemumble " << << '\n'; } out << std::ends; //write terminating null char
printing buffer gives:
mumblemumble 6 mumblemumble 7 mumblemumble 8 mumblemumble 9
(which confirms roll-over has taken place)
what makes streambuf use provided buffer cyclic output buffer (put area), without ever advancing buffer window in output sequence (stream). (using terminology http://en.cppreference.com/w/cpp/io/basic_streambuf)
now feel uncertain robustness , quality of implementation. please review , comment it.
this valid approach. overflow()
should return:
traits::eof() or throws exception if function fails. otherwise, returns value other traits::eof() indicate success.
e.g.:
virtual int_type overflow (int_type c) { // reset position start of buffer setp(pbase(), epptr()); return traits::not_eof(c); }
xsputn()
should write beginning of sequence end of buffer, rewind , write remaining sequence front of buffer. away default implementation of xsputn()
calls sputc(c)
each character , overflow()
when buffer full.
Comments
Post a Comment