1 //===----------------------------------------------------------------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 // <istream> 10 11 // basic_istream<charT,traits>& putback(char_type c); 12 13 #include <istream> 14 #include <cassert> 15 16 #include "test_macros.h" 17 18 template <class CharT> 19 struct testbuf 20 : public std::basic_streambuf<CharT> 21 { 22 typedef std::basic_string<CharT> string_type; 23 typedef std::basic_streambuf<CharT> base; 24 private: 25 string_type str_; 26 public: 27 28 testbuf() {} 29 testbuf(const string_type& str) 30 : str_(str) 31 { 32 base::setg(const_cast<CharT*>(str_.data()), 33 const_cast<CharT*>(str_.data()), 34 const_cast<CharT*>(str_.data()) + str_.size()); 35 } 36 37 CharT* eback() const {return base::eback();} 38 CharT* gptr() const {return base::gptr();} 39 CharT* egptr() const {return base::egptr();} 40 }; 41 42 int main(int, char**) 43 { 44 { 45 testbuf<char> sb(" 123456789"); 46 std::istream is(&sb); 47 is.get(); 48 is.get(); 49 is.get(); 50 is.putback('a'); 51 assert(is.bad()); 52 assert(is.gcount() == 0); 53 is.clear(); 54 is.putback('2'); 55 assert(is.good()); 56 assert(is.gcount() == 0); 57 is.putback('1'); 58 assert(is.good()); 59 assert(is.gcount() == 0); 60 is.putback(' '); 61 assert(is.good()); 62 assert(is.gcount() == 0); 63 is.putback(' '); 64 assert(is.bad()); 65 assert(is.gcount() == 0); 66 } 67 #ifndef TEST_HAS_NO_WIDE_CHARACTERS 68 { 69 testbuf<wchar_t> sb(L" 123456789"); 70 std::wistream is(&sb); 71 is.get(); 72 is.get(); 73 is.get(); 74 is.putback(L'a'); 75 assert(is.bad()); 76 assert(is.gcount() == 0); 77 is.clear(); 78 is.putback(L'2'); 79 assert(is.good()); 80 assert(is.gcount() == 0); 81 is.putback(L'1'); 82 assert(is.good()); 83 assert(is.gcount() == 0); 84 is.putback(L' '); 85 assert(is.good()); 86 assert(is.gcount() == 0); 87 is.putback(L' '); 88 assert(is.bad()); 89 assert(is.gcount() == 0); 90 } 91 #endif 92 #ifndef TEST_HAS_NO_EXCEPTIONS 93 { 94 testbuf<char> sb; 95 std::basic_istream<char> is(&sb); 96 is.exceptions(std::ios_base::badbit); 97 bool threw = false; 98 try { 99 is.putback('x'); 100 } catch (std::ios_base::failure&) { 101 threw = true; 102 } 103 assert(threw); 104 assert( is.bad()); 105 assert(!is.eof()); 106 assert( is.fail()); 107 } 108 #ifndef TEST_HAS_NO_WIDE_CHARACTERS 109 { 110 testbuf<wchar_t> sb; 111 std::basic_istream<wchar_t> is(&sb); 112 is.exceptions(std::ios_base::badbit); 113 bool threw = false; 114 try { 115 is.putback(L'x'); 116 } catch (std::ios_base::failure&) { 117 threw = true; 118 } 119 assert(threw); 120 assert( is.bad()); 121 assert(!is.eof()); 122 assert( is.fail()); 123 } 124 #endif 125 #endif // TEST_HAS_NO_EXCEPTIONS 126 127 return 0; 128 } 129