growing_range_test.cpp 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "common/growing_range.h"
  5. #include <gtest/gtest.h>
  6. #include <vector>
  7. namespace Carbon {
  8. namespace {
  9. TEST(GrowingRangeTest, TestUnchanged) {
  10. std::vector<int> v = {1, 2, 3, 4, 5};
  11. int k = 0;
  12. for (int n : GrowingRange(v)) {
  13. EXPECT_EQ(n, ++k);
  14. }
  15. }
  16. TEST(GrowingRangeTest, TestGrowWithRealloc) {
  17. std::vector<int> expected = {3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0};
  18. std::vector<int> v;
  19. v.reserve(1);
  20. v.push_back(3);
  21. EXPECT_LT(v.capacity(), expected.size());
  22. int i = 0;
  23. for (int n : GrowingRange(v)) {
  24. // Append n copies of n - 1.
  25. v.insert(v.end(), n, n - 1);
  26. EXPECT_EQ(n, expected[i++]);
  27. }
  28. }
  29. TEST(GrowingRangeTest, TestNoReference) {
  30. std::vector<int> v;
  31. // Use `decltype(auto)` to capture the type of the element including whether
  32. // it's a reference.
  33. for (decltype(auto) elem : GrowingRange(v)) {
  34. // The type of `elem` should be `int`, not `int&`.
  35. static_assert(std::same_as<decltype(elem), int>);
  36. }
  37. }
  38. } // namespace
  39. } // namespace Carbon