Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-01-18 09:38:11

0001 // Copyright 2019 Hans Dembinski
0002 //
0003 // Distributed under the Boost Software License, Version 1.0.
0004 // (See accompanying file LICENSE_1_0.txt
0005 // or copy at http://www.boost.org/LICENSE_1_0.txt)
0006 
0007 #ifndef BOOST_HISTOGRAM_DETAIL_COUNTING_STREAMBUF_HPP
0008 #define BOOST_HISTOGRAM_DETAIL_COUNTING_STREAMBUF_HPP
0009 
0010 #include <boost/core/exchange.hpp>
0011 #include <ostream>
0012 #include <streambuf>
0013 
0014 namespace boost {
0015 namespace histogram {
0016 namespace detail {
0017 
0018 // detect how many characters will be printed by formatted output
0019 template <class CharT, class Traits = std::char_traits<CharT>>
0020 struct counting_streambuf : std::basic_streambuf<CharT, Traits> {
0021   using base_t = std::basic_streambuf<CharT, Traits>;
0022   using typename base_t::char_type;
0023   using typename base_t::int_type;
0024 
0025   std::streamsize* p_count;
0026 
0027   counting_streambuf(std::streamsize& c) : p_count(&c) {}
0028 
0029   std::streamsize xsputn(const char_type* /* s */, std::streamsize n) override {
0030     *p_count += n;
0031     return n;
0032   }
0033 
0034   int_type overflow(int_type ch) override {
0035     ++*p_count;
0036     return ch;
0037   }
0038 };
0039 
0040 template <class C, class T>
0041 struct count_guard {
0042   using bos = std::basic_ostream<C, T>;
0043   using bsb = std::basic_streambuf<C, T>;
0044 
0045   counting_streambuf<C, T> csb;
0046   bos* p_os;
0047   bsb* p_rdbuf;
0048 
0049   count_guard(bos& os, std::streamsize& s) : csb(s), p_os(&os), p_rdbuf(os.rdbuf(&csb)) {}
0050 
0051   count_guard(count_guard&& o)
0052       : csb(o.csb), p_os(boost::exchange(o.p_os, nullptr)), p_rdbuf(o.p_rdbuf) {}
0053 
0054   count_guard& operator=(count_guard&& o) {
0055     if (this != &o) {
0056       csb = std::move(o.csb);
0057       p_os = boost::exchange(o.p_os, nullptr);
0058       p_rdbuf = o.p_rdbuf;
0059     }
0060     return *this;
0061   }
0062 
0063   ~count_guard() {
0064     if (p_os) p_os->rdbuf(p_rdbuf);
0065   }
0066 };
0067 
0068 template <class C, class T>
0069 count_guard<C, T> make_count_guard(std::basic_ostream<C, T>& os, std::streamsize& s) {
0070   return {os, s};
0071 }
0072 
0073 } // namespace detail
0074 } // namespace histogram
0075 } // namespace boost
0076 
0077 #endif