xref: /llvm-project/libcxx/test/std/input.output/string.streams/stringbuf/stringbuf.members/view.pass.cpp (revision 838f2890fd30295b771908e234fb06cb169cf355)
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 // UNSUPPORTED: c++03, c++11, c++14, c++17
10 
11 // <sstream>
12 
13 // template <class charT, class traits = char_traits<charT>, class Allocator = allocator<charT> >
14 // class basic_stringbuf
15 
16 // basic_string_view<charT, traits> view() const noexcept;
17 
18 #include <sstream>
19 #include <cassert>
20 #include <type_traits>
21 
22 #include "make_string.h"
23 #include "test_macros.h"
24 
25 #define STR(S) MAKE_STRING(CharT, S)
26 #define SV(S) MAKE_STRING_VIEW(CharT, S)
27 
28 template <class CharT>
29 struct my_char_traits : public std::char_traits<CharT> {};
30 
31 template <class CharT>
test()32 static void test() {
33   std::basic_stringbuf<CharT> buf(STR("testing"));
34   static_assert(noexcept(buf.view()));
35   assert(buf.view() == SV("testing"));
36   buf.str(STR("another test"));
37   assert(buf.view() == SV("another test"));
38 
39   std::basic_stringbuf<CharT> robuf(STR("foo"), std::ios_base::in);
40   assert(robuf.view() == SV("foo"));
41 
42   std::basic_stringbuf<CharT> nbuf(STR("not used"), 0);
43   assert(nbuf.view() == std::basic_string_view<CharT>());
44 
45   const std::basic_stringbuf<CharT> cbuf(STR("abc"));
46   static_assert(noexcept(cbuf.view()));
47   assert(cbuf.view() == SV("abc"));
48 
49   std::basic_stringbuf<CharT, my_char_traits<CharT>> tbuf;
50   static_assert(std::is_same_v<decltype(tbuf.view()), std::basic_string_view<CharT, my_char_traits<CharT>>>);
51 }
52 
53 struct StringBuf : std::stringbuf {
54   using basic_stringbuf::basic_stringbuf;
public_setgStringBuf55   void public_setg(int a, int b, int c) {
56     char* p = eback();
57     this->setg(p + a, p + b, p + c);
58   }
59 };
60 
test_altered_sequence_pointers()61 static void test_altered_sequence_pointers() {
62   {
63     auto src = StringBuf("hello world", std::ios_base::in);
64     src.public_setg(4, 6, 9);
65     std::stringbuf dest;
66     dest = std::move(src);
67     assert(dest.view() == dest.str());
68     LIBCPP_ASSERT(dest.view() == "o wor");
69   }
70   {
71     auto src = StringBuf("hello world", std::ios_base::in);
72     src.public_setg(4, 6, 9);
73     std::stringbuf dest;
74     dest.swap(src);
75     assert(dest.view() == dest.str());
76     LIBCPP_ASSERT(dest.view() == "o wor");
77   }
78 }
79 
main(int,char **)80 int main(int, char**) {
81   test<char>();
82 #ifndef TEST_HAS_NO_WIDE_CHARACTERS
83   test<wchar_t>();
84 #endif
85   test_altered_sequence_pointers();
86   return 0;
87 }
88