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& str) const // constexpr since C++20
12
13#include <string>
14#include <cassert>
15
16#include "test_macros.h"
17#include "min_allocator.h"
18
19TEST_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
27template <class S>
28TEST_CONSTEXPR_CXX20 void test(const S& s, const S& str, int x) {
29 LIBCPP_ASSERT_NOEXCEPT(s.compare(str));
30 assert(sign(s.compare(str)) == sign(x));
31}
32
33template <class S>
34TEST_CONSTEXPR_CXX20 void test_string() {
35 test(S(""), S(""), 0);
36 test(S(""), S("abcde"), -5);
37 test(S(""), S("abcdefghij"), -10);
38 test(S(""), S("abcdefghijklmnopqrst"), -20);
39 test(S("abcde"), S(""), 5);
40 test(S("abcde"), S("abcde"), 0);
41 test(S("abcde"), S("abcdefghij"), -5);
42 test(S("abcde"), S("abcdefghijklmnopqrst"), -15);
43 test(S("abcdefghij"), S(""), 10);
44 test(S("abcdefghij"), S("abcde"), 5);
45 test(S("abcdefghij"), S("abcdefghij"), 0);
46 test(S("abcdefghij"), S("abcdefghijklmnopqrst"), -10);
47 test(S("abcdefghijklmnopqrst"), S(""), 20);
48 test(S("abcdefghijklmnopqrst"), S("abcde"), 15);
49 test(S("abcdefghijklmnopqrst"), S("abcdefghij"), 10);
50 test(S("abcdefghijklmnopqrst"), S("abcdefghijklmnopqrst"), 0);
51}
52
53TEST_CONSTEXPR_CXX20 bool test() {
54 test_string<std::string>();
55#if TEST_STD_VER >= 11
56 test_string<std::basic_string<char, std::char_traits<char>, min_allocator<char> > >();
57 { // LWG 2946
58 std::string s = " !";
59 assert(s.compare({"abc", 1}) < 0);
60 }
61#endif
62
63 return true;
64}
65
66int main(int, char**) {
67 test();
68#if TEST_STD_VER > 17
69 static_assert(test());
70#endif
71
72 return 0;
73}
74

source code of libcxx/test/std/strings/basic.string/string.ops/string_compare/string.pass.cpp