Home | History | Annotate | Download | only in ostream.manip
      1 //===----------------------------------------------------------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is dual licensed under the MIT and the University of Illinois Open
      6 // Source Licenses. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 
     10 // <ostream>
     11 
     12 // template <class charT, class traits = char_traits<charT> >
     13 //   class basic_ostream;
     14 
     15 // template <class charT, class traits>
     16 //   basic_ostream<charT,traits>& endl(basic_ostream<charT,traits>& os);
     17 
     18 #include <ostream>
     19 #include <cassert>
     20 
     21 int sync_called = 0;
     22 
     23 template <class CharT>
     24 class testbuf
     25     : public std::basic_streambuf<CharT>
     26 {
     27     typedef std::basic_streambuf<CharT> base;
     28     std::basic_string<CharT> str_;
     29 public:
     30     testbuf()
     31     {
     32     }
     33 
     34     std::basic_string<CharT> str() const
     35         {return std::basic_string<CharT>(base::pbase(), base::pptr());}
     36 
     37 protected:
     38 
     39     virtual typename base::int_type
     40         overflow(typename base::int_type __c = base::traits_type::eof())
     41         {
     42             if (__c != base::traits_type::eof())
     43             {
     44                 int n = str_.size();
     45                 str_.push_back(__c);
     46                 str_.resize(str_.capacity());
     47                 base::setp(const_cast<CharT*>(str_.data()),
     48                            const_cast<CharT*>(str_.data() + str_.size()));
     49                 base::pbump(n+1);
     50             }
     51             return __c;
     52         }
     53 
     54     virtual int
     55         sync()
     56         {
     57             ++sync_called;
     58             return 0;
     59         }
     60 };
     61 
     62 int main()
     63 {
     64     {
     65         testbuf<char> sb;
     66         std::ostream os(&sb);
     67         endl(os);
     68         assert(sb.str() == "\n");
     69         assert(sync_called == 1);
     70         assert(os.good());
     71     }
     72     {
     73         testbuf<wchar_t> sb;
     74         std::wostream os(&sb);
     75         endl(os);
     76         assert(sb.str() == L"\n");
     77         assert(sync_called == 2);
     78         assert(os.good());
     79     }
     80 }
     81