110 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// int_type peek();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(" 1\n2345\n6");47 std::istream is(&sb);48 assert(is.peek() == ' ');49 assert(!is.eof());50 assert(!is.fail());51 assert(is.gcount() == 0);52 is.get();53 assert(is.peek() == '1');54 assert(!is.eof());55 assert(!is.fail());56 assert(is.gcount() == 0);57 }58#ifndef TEST_HAS_NO_WIDE_CHARACTERS59 {60 testbuf<wchar_t> sb(L" 1\n2345\n6");61 std::wistream is(&sb);62 assert(is.peek() == L' ');63 assert(!is.eof());64 assert(!is.fail());65 assert(is.gcount() == 0);66 is.get();67 assert(is.peek() == L'1');68 assert(!is.eof());69 assert(!is.fail());70 assert(is.gcount() == 0);71 }72#endif73#ifndef TEST_HAS_NO_EXCEPTIONS74 {75 testbuf<char> sb;76 std::basic_istream<char> is(&sb);77 is.exceptions(std::ios_base::eofbit);78 bool threw = false;79 try {80 is.peek();81 } catch (std::ios_base::failure&) {82 threw = true;83 }84 assert(threw);85 assert(!is.bad());86 assert( is.eof());87 assert(!is.fail());88 }89#ifndef TEST_HAS_NO_WIDE_CHARACTERS90 {91 testbuf<wchar_t> sb;92 std::basic_istream<wchar_t> is(&sb);93 is.exceptions(std::ios_base::eofbit);94 bool threw = false;95 try {96 is.peek();97 } catch (std::ios_base::failure&) {98 threw = true;99 }100 assert(threw);101 assert(!is.bad());102 assert( is.eof());103 assert(!is.fail());104 }105#endif106#endif // TEST_HAS_NO_EXCEPTIONS107 108 return 0;109}110