brintos

brintos / llvm-project-archived public Read only

0
0
Text · 2.1 KiB · 2308524 Raw
89 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// <string>10 11// void shrink_to_fit(); // constexpr since C++2012 13#include <cassert>14#include <string>15 16#include "asan_testing.h"17#include "increasing_allocator.h"18#include "min_allocator.h"19#include "test_macros.h"20 21template <class S>22TEST_CONSTEXPR_CXX20 void test(S& s) {23  typename S::size_type old_cap = s.capacity();24  S s0                          = s;25  s.shrink_to_fit();26  LIBCPP_ASSERT(s.__invariants());27  assert(s == s0);28  assert(s.capacity() <= old_cap);29  assert(s.capacity() >= s.size());30  LIBCPP_ASSERT(is_string_asan_correct(s));31}32 33template <class S>34TEST_CONSTEXPR_CXX20 void test_string() {35  S s;36  test(s);37 38  s.assign(10, 'a');39  s.erase(5);40  test(s);41 42  s.assign(50, 'a');43  s.erase(5);44  test(s);45 46  s.assign(100, 'a');47  s.erase(50);48  test(s);49 50  s.assign(100, 'a');51  for (int i = 0; i <= 9; ++i) {52    s.erase(90 - 10 * i);53    test(s);54  }55}56 57TEST_CONSTEXPR_CXX20 bool test() {58  test_string<std::string>();59#if TEST_STD_VER >= 1160  test_string<std::basic_string<char, std::char_traits<char>, min_allocator<char>>>();61  test_string<std::basic_string<char, std::char_traits<char>, safe_allocator<char>>>();62#endif63 64#if TEST_STD_VER >= 2365  { // Make sure shrink_to_fit never increases capacity66    // See: https://llvm.org/PR9516167    std::basic_string<char, std::char_traits<char>, increasing_allocator<char>> s{68        "String does not fit in the internal buffer"};69    std::size_t capacity = s.capacity();70    std::size_t size     = s.size();71    s.shrink_to_fit();72    assert(s.capacity() <= capacity);73    assert(s.size() == size);74    LIBCPP_ASSERT(is_string_asan_correct(s));75  }76#endif77 78  return true;79}80 81int main(int, char**) {82  test();83#if TEST_STD_VER > 1784  static_assert(test());85#endif86 87  return 0;88}89