-
Notifications
You must be signed in to change notification settings - Fork 166
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
282 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
#ifndef CALLBACK_STREAMBUF_H | ||
#define CALLBACK_STREAMBUF_H | ||
|
||
#include <array> | ||
#include <iostream> | ||
|
||
template<typename Callback, std::size_t Size, class Char = char> | ||
class callback_streambuf : public std::basic_streambuf<Char> | ||
{ | ||
public: | ||
using base_type = std::streambuf; | ||
using char_type = typename base_type::char_type; | ||
using int_type = typename base_type::int_type; | ||
|
||
callback_streambuf(Callback callback) | ||
: buffer_{}, | ||
callback_(callback) | ||
{ | ||
base_type::setp(buffer_.begin(), buffer_.end()); | ||
} | ||
|
||
protected: | ||
int sync() | ||
{ | ||
bool ok = callback_(base_type::pbase(), | ||
base_type::pptr() - base_type::pbase()); | ||
base_type::setp(buffer_.begin(), buffer_.end()); | ||
return ok ? 0 : -1; | ||
} | ||
|
||
int_type overflow(int_type ch) | ||
{ | ||
int ret = sync(); | ||
if (ch == base_type::traits_type::eof()) | ||
{ | ||
return ch; | ||
} | ||
base_type::sputc(ch); | ||
return ret == 0 ? 0 : base_type::traits_type::eof(); | ||
} | ||
|
||
private: | ||
std::array<char_type, Size> buffer_; | ||
Callback callback_; | ||
}; | ||
|
||
#endif |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters