| 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++20 } } |
| 19 | // { dg-skip-if "" { *-*-* } { "-fno-char8_t" } } |
| 20 | |
| 21 | #include <string> |
| 22 | #include <memory_resource> |
| 23 | #include <testsuite_hooks.h> |
| 24 | #include <testsuite_allocator.h> |
| 25 | |
| 26 | // C++2a N4810 21.3.5 [basic.string.hash] |
| 27 | // If S is one of these string types, SV is the corresponding string view type, |
| 28 | // and s is an object of type S, then hash<S>()(s) == hash<SV>()(SV(s)). |
| 29 | |
| 30 | template<typename S> |
| 31 | bool |
| 32 | test(const S& s) |
| 33 | { |
| 34 | using std::hash; |
| 35 | using SV = std::basic_string_view<typename S::value_type>; |
| 36 | return hash<S>()(s) == hash<SV>()(SV(s)); |
| 37 | } |
| 38 | |
| 39 | void |
| 40 | test01() |
| 41 | { |
| 42 | VERIFY( test(std::string("a narrow string")) ); |
| 43 | VERIFY( test(std::u8string(u8"a utf-8 string")) ); |
| 44 | #if _GLIBCXX_USE_CXX11_ABI |
| 45 | VERIFY( test(std::pmr::string("a narrow string, but with PMR!")) ); |
| 46 | VERIFY( test(std::pmr::u8string(u8"a utf-8 string, but with PMR!")) ); |
| 47 | #endif |
| 48 | } |
| 49 | |
| 50 | void |
| 51 | test02() |
| 52 | { |
| 53 | using std::hash; |
| 54 | std::string native("a string, a string, my stringdom for a string"); |
| 55 | std::u8string utf8(u8"a string, a string, my stringdom for a string"); |
| 56 | VERIFY( hash<std::string>()(native) == hash<std::u8string>()(utf8) ); |
| 57 | } |
| 58 | |
| 59 | void |
| 60 | test03() |
| 61 | { |
| 62 | using Alloc = __gnu_test::SimpleAllocator<char8_t>; |
| 63 | using Stringu8 = std::basic_string<char8_t, std::char_traits<char8_t>, Alloc>; |
| 64 | |
| 65 | // LWG 3705. Hashability shouldn't depend on basic_string's allocator |
| 66 | VERIFY( test(Stringu8(u8"a utf-8 string, with custom allocator")) ); |
| 67 | } |
| 68 | |
| 69 | int |
| 70 | main() |
| 71 | { |
| 72 | test01(); |
| 73 | test02(); |
| 74 | test03(); |
| 75 | } |