| 1 | // Copyright (C) 2019-2025 Free Software Foundation, Inc. |
| 2 | // |
| 3 | // This file is part of the GNU ISO C++ Library. This library is free |
| 4 | // software; you can redistribute it and/or modify it under the |
| 5 | // terms of the GNU General Public License as published by the |
| 6 | // Free Software Foundation; either version 3, or (at your option) |
| 7 | // any later version. |
| 8 | |
| 9 | // This library is distributed in the hope that it will be useful, |
| 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | // GNU General Public License for more details. |
| 13 | |
| 14 | // You should have received a copy of the GNU General Public License along |
| 15 | // with this library; see the file COPYING3. If not see |
| 16 | // <http://www.gnu.org/licenses/>. |
| 17 | |
| 18 | // { dg-do run { target c++17 } } |
| 19 | |
| 20 | #include <string> |
| 21 | #include <memory_resource> |
| 22 | #include <testsuite_hooks.h> |
| 23 | #include <testsuite_allocator.h> |
| 24 | |
| 25 | // C++17 24.3.5 [basic.string.hash] |
| 26 | // If S is one of these string types, SV is the corresponding string view type, |
| 27 | // and s is an object of type S, then hash<S>()(s) == hash<SV>()(SV(s)). |
| 28 | |
| 29 | template<typename S> |
| 30 | bool |
| 31 | test(const S& s) |
| 32 | { |
| 33 | using std::hash; |
| 34 | using SV = std::basic_string_view<typename S::value_type>; |
| 35 | return hash<S>()(s) == hash<SV>()(SV(s)); |
| 36 | } |
| 37 | |
| 38 | void |
| 39 | test01() |
| 40 | { |
| 41 | VERIFY( test(std::string("a narrow string")) ); |
| 42 | VERIFY( test(std::u16string(u"a utf-16 string")) ); |
| 43 | VERIFY( test(std::u32string(U"a utf-32 string")) ); |
| 44 | VERIFY( test(std::wstring(L"a wide string")) ); |
| 45 | } |
| 46 | |
| 47 | void |
| 48 | test02() |
| 49 | { |
| 50 | #if _GLIBCXX_USE_CXX11_ABI |
| 51 | VERIFY( test(std::pmr::string("a narrow string, but with PMR!")) ); |
| 52 | VERIFY( test(std::pmr::u16string(u"a utf-16 string, but with PMR!")) ); |
| 53 | VERIFY( test(std::pmr::u32string(U"a utf-32 string, but with PMR!")) ); |
| 54 | VERIFY( test(std::pmr::wstring(L"a wide string, but with PMR!")) ); |
| 55 | #endif |
| 56 | } |
| 57 | |
| 58 | template<typename C> |
| 59 | using String |
| 60 | = std::basic_string<C, std::char_traits<C>, __gnu_test::SimpleAllocator<C>>; |
| 61 | |
| 62 | void |
| 63 | test03() |
| 64 | { |
| 65 | // LWG 3705. Hashability shouldn't depend on basic_string's allocator |
| 66 | VERIFY( test(String<char>("a narrow string")) ); |
| 67 | VERIFY( test(String<char16_t>(u"a utf-16 string")) ); |
| 68 | VERIFY( test(String<char32_t>(U"a utf-32 string")) ); |
| 69 | VERIFY( test(String<wchar_t>(L"a wide string")) ); |
| 70 | } |
| 71 | |
| 72 | int |
| 73 | main() |
| 74 | { |
| 75 | test01(); |
| 76 | test02(); |
| 77 | test03(); |
| 78 | } |