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 // operator<<(const void* val); 16 17 #include <ostream> 18 #include <cassert> 19 20 template <class CharT> 21 class testbuf 22 : public std::basic_streambuf<CharT> 23 { 24 typedef std::basic_streambuf<CharT> base; 25 std::basic_string<CharT> str_; 26 public: 27 testbuf() 28 { 29 } 30 31 std::basic_string<CharT> str() const 32 {return std::basic_string<CharT>(base::pbase(), base::pptr());} 33 34 protected: 35 36 virtual typename base::int_type 37 overflow(typename base::int_type ch = base::traits_type::eof()) 38 { 39 if (ch != base::traits_type::eof()) 40 { 41 int n = static_cast<int>(str_.size()); 42 str_.push_back(static_cast<CharT>(ch)); 43 str_.resize(str_.capacity()); 44 base::setp(const_cast<CharT*>(str_.data()), 45 const_cast<CharT*>(str_.data() + str_.size())); 46 base::pbump(n+1); 47 } 48 return ch; 49 } 50 }; 51 52 int main() 53 { 54 { 55 std::ostream os((std::streambuf*)0); 56 const void* n = 0; 57 os << n; 58 assert(os.bad()); 59 assert(os.fail()); 60 } 61 { 62 testbuf<char> sb1; 63 std::ostream os1(&sb1); 64 int n1; 65 os1 << &n1; 66 assert(os1.good()); 67 std::string s1(sb1.str()); 68 69 testbuf<char> sb2; 70 std::ostream os2(&sb2); 71 int n2; 72 os2 << &n2; 73 assert(os2.good()); 74 std::string s2(sb2.str()); 75 76 // %p is implementation defined. Instead of validating the 77 // output, at least ensure that it does not generate an empty 78 // string. Also make sure that given two distinct addresses, the 79 // output of %p is different. 80 assert(!s1.empty()); 81 assert(!s2.empty()); 82 assert(s1 != s2); 83 } 84 { 85 testbuf<char> sb; 86 std::ostream os(&sb); 87 const void* n = &sb; 88 os << n; 89 assert(os.good()); 90 } 91 } 92