1 // Copyright 2019 Hans Dembinski
3 // Distributed under the Boost Software License, Version 1.0.
4 // (See accompanying file LICENSE_1_0.txt
5 // or copy at http://www.boost.org/LICENSE_1_0.txt)
7 #ifndef BOOST_HISTOGRAM_DETAIL_COUNTING_STREAMBUF_HPP
8 #define BOOST_HISTOGRAM_DETAIL_COUNTING_STREAMBUF_HPP
10 #include <boost/core/exchange.hpp>
18 // detect how many characters will be printed by formatted output
19 template <class CharT, class Traits = std::char_traits<CharT>>
20 struct counting_streambuf : std::basic_streambuf<CharT, Traits> {
21 using base_t = std::basic_streambuf<CharT, Traits>;
22 using typename base_t::char_type;
23 using typename base_t::int_type;
25 std::streamsize* p_count;
27 counting_streambuf(std::streamsize& c) : p_count(&c) {}
29 std::streamsize xsputn(const char_type* /* s */, std::streamsize n) override {
34 int_type overflow(int_type ch) override {
40 template <class C, class T>
42 using bos = std::basic_ostream<C, T>;
43 using bsb = std::basic_streambuf<C, T>;
45 counting_streambuf<C, T> csb;
49 count_guard(bos& os, std::streamsize& s) : csb(s), p_os(&os), p_rdbuf(os.rdbuf(&csb)) {}
51 count_guard(count_guard&& o)
52 : csb(o.csb), p_os(boost::exchange(o.p_os, nullptr)), p_rdbuf(o.p_rdbuf) {}
54 count_guard& operator=(count_guard&& o) {
56 csb = std::move(o.csb);
57 p_os = boost::exchange(o.p_os, nullptr);
64 if (p_os) p_os->rdbuf(p_rdbuf);
68 template <class C, class T>
69 count_guard<C, T> make_count_guard(std::basic_ostream<C, T>& os, std::streamsize& s) {
74 } // namespace histogram