130 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8 9// <istream>10 11// basic_istream<charT,traits>& putback(char_type c);12 13#include <istream>14#include <cassert>15#include <streambuf>16 17#include "test_macros.h"18 19template <class CharT>20struct testbuf21 : public std::basic_streambuf<CharT>22{23 typedef std::basic_string<CharT> string_type;24 typedef std::basic_streambuf<CharT> base;25private:26 string_type str_;27public:28 29 testbuf() {}30 testbuf(const string_type& str)31 : str_(str)32 {33 base::setg(const_cast<CharT*>(str_.data()),34 const_cast<CharT*>(str_.data()),35 const_cast<CharT*>(str_.data()) + str_.size());36 }37 38 CharT* eback() const {return base::eback();}39 CharT* gptr() const {return base::gptr();}40 CharT* egptr() const {return base::egptr();}41};42 43int main(int, char**)44{45 {46 testbuf<char> sb(" 123456789");47 std::istream is(&sb);48 is.get();49 is.get();50 is.get();51 is.putback('a');52 assert(is.bad());53 assert(is.gcount() == 0);54 is.clear();55 is.putback('2');56 assert(is.good());57 assert(is.gcount() == 0);58 is.putback('1');59 assert(is.good());60 assert(is.gcount() == 0);61 is.putback(' ');62 assert(is.good());63 assert(is.gcount() == 0);64 is.putback(' ');65 assert(is.bad());66 assert(is.gcount() == 0);67 }68#ifndef TEST_HAS_NO_WIDE_CHARACTERS69 {70 testbuf<wchar_t> sb(L" 123456789");71 std::wistream is(&sb);72 is.get();73 is.get();74 is.get();75 is.putback(L'a');76 assert(is.bad());77 assert(is.gcount() == 0);78 is.clear();79 is.putback(L'2');80 assert(is.good());81 assert(is.gcount() == 0);82 is.putback(L'1');83 assert(is.good());84 assert(is.gcount() == 0);85 is.putback(L' ');86 assert(is.good());87 assert(is.gcount() == 0);88 is.putback(L' ');89 assert(is.bad());90 assert(is.gcount() == 0);91 }92#endif93#ifndef TEST_HAS_NO_EXCEPTIONS94 {95 testbuf<char> sb;96 std::basic_istream<char> is(&sb);97 is.exceptions(std::ios_base::badbit);98 bool threw = false;99 try {100 is.putback('x');101 } catch (std::ios_base::failure&) {102 threw = true;103 }104 assert(threw);105 assert( is.bad());106 assert(!is.eof());107 assert( is.fail());108 }109#ifndef TEST_HAS_NO_WIDE_CHARACTERS110 {111 testbuf<wchar_t> sb;112 std::basic_istream<wchar_t> is(&sb);113 is.exceptions(std::ios_base::badbit);114 bool threw = false;115 try {116 is.putback(L'x');117 } catch (std::ios_base::failure&) {118 threw = true;119 }120 assert(threw);121 assert( is.bad());122 assert(!is.eof());123 assert( is.fail());124 }125#endif126#endif // TEST_HAS_NO_EXCEPTIONS127 128 return 0;129}130