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>& unget(); 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 testbuftestbuf28 testbuf() {} testbuftestbuf29 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 ebacktestbuf37 CharT* eback() const {return base::eback();} gptrtestbuf38 CharT* gptr() const {return base::gptr();} egptrtestbuf39 CharT* egptr() const {return base::egptr();} 40 }; 41 main(int,char **)42int 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.unget(); 51 assert(is.good()); 52 assert(is.gcount() == 0); 53 is.unget(); 54 assert(is.good()); 55 assert(is.gcount() == 0); 56 is.unget(); 57 assert(is.good()); 58 assert(is.gcount() == 0); 59 is.unget(); 60 assert(is.bad()); 61 assert(is.gcount() == 0); 62 } 63 { 64 testbuf<wchar_t> sb(L" 123456789"); 65 std::wistream is(&sb); 66 is.get(); 67 is.get(); 68 is.get(); 69 is.unget(); 70 assert(is.good()); 71 assert(is.gcount() == 0); 72 is.unget(); 73 assert(is.good()); 74 assert(is.gcount() == 0); 75 is.unget(); 76 assert(is.good()); 77 assert(is.gcount() == 0); 78 is.unget(); 79 assert(is.bad()); 80 assert(is.gcount() == 0); 81 } 82 #ifndef TEST_HAS_NO_EXCEPTIONS 83 { 84 testbuf<char> sb; 85 std::basic_istream<char> is(&sb); 86 is.exceptions(std::ios_base::badbit); 87 bool threw = false; 88 try { 89 is.unget(); 90 } catch (std::ios_base::failure&) { 91 threw = true; 92 } 93 assert(threw); 94 assert( is.bad()); 95 assert(!is.eof()); 96 assert( is.fail()); 97 } 98 { 99 testbuf<wchar_t> sb; 100 std::basic_istream<wchar_t> is(&sb); 101 is.exceptions(std::ios_base::badbit); 102 bool threw = false; 103 try { 104 is.unget(); 105 } catch (std::ios_base::failure&) { 106 threw = true; 107 } 108 assert(threw); 109 assert( is.bad()); 110 assert(!is.eof()); 111 assert( is.fail()); 112 } 113 #endif 114 115 return 0; 116 } 117