109 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8 9// UNSUPPORTED: no-exceptions10 11// <string>12 13// size_type max_size() const; // constexpr since C++2014 15// NOTE: asan and msan will fail for one of two reasons16// 1. If allocator_may_return_null=0 then they will fail because the allocation17// returns null.18// 2. If allocator_may_return_null=1 then they will fail because the allocation19// is too large to succeed.20// UNSUPPORTED: sanitizer-new-delete21 22#include <string>23#include <cassert>24#include <new>25 26#include "test_macros.h"27#include "min_allocator.h"28 29template <class S>30TEST_CONSTEXPR_CXX20 void test_resize_max_size_minus_1(const S& s) {31 S s2(s);32 const std::size_t sz = s2.max_size() - 1;33 try {34 s2.resize(sz, 'x');35 } catch (const std::bad_alloc&) {36 return;37 }38 assert(s2.size() == sz);39}40 41template <class S>42TEST_CONSTEXPR_CXX20 void test_resize_max_size(const S& s) {43 S s2(s);44 const std::size_t sz = s2.max_size();45 try {46 s2.resize(sz, 'x');47 } catch (const std::bad_alloc&) {48 return;49 }50 assert(s2.size() == sz);51}52 53template <class S>54TEST_CONSTEXPR_CXX20 void test_string() {55 {56 S s;57 assert(s.max_size() >= s.size());58 assert(s.max_size() > 0);59 if (!TEST_IS_CONSTANT_EVALUATED) {60 test_resize_max_size_minus_1(s);61 test_resize_max_size(s);62 }63 }64 {65 S s("123");66 assert(s.max_size() >= s.size());67 assert(s.max_size() > 0);68 if (!TEST_IS_CONSTANT_EVALUATED) {69 test_resize_max_size_minus_1(s);70 test_resize_max_size(s);71 }72 }73 {74 S s("12345678901234567890123456789012345678901234567890");75 assert(s.max_size() >= s.size());76 assert(s.max_size() > 0);77 if (!TEST_IS_CONSTANT_EVALUATED) {78 test_resize_max_size_minus_1(s);79 test_resize_max_size(s);80 }81 }82}83 84TEST_CONSTEXPR_CXX20 bool test() {85 test_string<std::string>();86#if TEST_STD_VER >= 1187 test_string<std::basic_string<char, std::char_traits<char>, min_allocator<char> > >();88 test_string<std::basic_string<char, std::char_traits<char>, tiny_size_allocator<64, char> > >();89#endif90 91 { // Test resizing where we can assume that the allocation succeeds92 std::basic_string<char, std::char_traits<char>, tiny_size_allocator<32, char> > str;93 auto max_size = str.max_size();94 str.resize(max_size);95 assert(str.size() == max_size);96 }97 98 return true;99}100 101int main(int, char**) {102 test();103#if TEST_STD_VER >= 20104 static_assert(test());105#endif106 107 return 0;108}109