xref: /llvm-project/libcxx/test/std/strings/basic.string/string.ops/string_compare/string_view.pass.cpp (revision 6e1dcc9335116f650d68cdbed12bbb34a99b2d9b)
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 // <string>
10 
11 // int compare(const basic_string_view sv) const // constexpr since C++20
12 
13 #include <string>
14 #include <cassert>
15 
16 #include "test_macros.h"
17 #include "min_allocator.h"
18 
sign(int x)19 TEST_CONSTEXPR_CXX20 int sign(int x) {
20   if (x == 0)
21     return 0;
22   if (x < 0)
23     return -1;
24   return 1;
25 }
26 
27 template <class S, class SV>
test(const S & s,SV sv,int x)28 TEST_CONSTEXPR_CXX20 void test(const S& s, SV sv, int x) {
29   LIBCPP_ASSERT_NOEXCEPT(s.compare(sv));
30   assert(sign(s.compare(sv)) == sign(x));
31 }
32 
33 template <class CharT, template <class> class Alloc>
test_string()34 TEST_CONSTEXPR_CXX20 void test_string() {
35   using S  = std::basic_string<CharT, std::char_traits<CharT>, Alloc<CharT> >;
36   using SV = std::basic_string_view<CharT, std::char_traits<CharT> >;
37 
38   test(S(""), SV(""), 0);
39   test(S(""), SV("abcde"), -5);
40   test(S(""), SV("abcdefghij"), -10);
41   test(S(""), SV("abcdefghijklmnopqrst"), -20);
42   test(S("abcde"), SV(""), 5);
43   test(S("abcde"), SV("abcde"), 0);
44   test(S("abcde"), SV("abcdefghij"), -5);
45   test(S("abcde"), SV("abcdefghijklmnopqrst"), -15);
46   test(S("abcdefghij"), SV(""), 10);
47   test(S("abcdefghij"), SV("abcde"), 5);
48   test(S("abcdefghij"), SV("abcdefghij"), 0);
49   test(S("abcdefghij"), SV("abcdefghijklmnopqrst"), -10);
50   test(S("abcdefghijklmnopqrst"), SV(""), 20);
51   test(S("abcdefghijklmnopqrst"), SV("abcde"), 15);
52   test(S("abcdefghijklmnopqrst"), SV("abcdefghij"), 10);
53   test(S("abcdefghijklmnopqrst"), SV("abcdefghijklmnopqrst"), 0);
54 }
55 
test()56 TEST_CONSTEXPR_CXX20 bool test() {
57   test_string<char, std::allocator>();
58 #if TEST_STD_VER >= 11
59   test_string<char, min_allocator>();
60 #endif
61 
62   return true;
63 }
64 
main(int,char **)65 int main(int, char**) {
66   test();
67 #if TEST_STD_VER > 17
68   static_assert(test());
69 #endif
70 
71   return 0;
72 }
73