contains_unittest.cc 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2020 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "base/containers/contains.h"
  5. #include <set>
  6. #include <string>
  7. #include "base/containers/flat_set.h"
  8. #include "base/functional/identity.h"
  9. #include "base/strings/string_piece.h"
  10. #include "base/strings/string_util.h"
  11. #include "testing/gmock/include/gmock/gmock.h"
  12. #include "testing/gtest/include/gtest/gtest.h"
  13. namespace base {
  14. TEST(ContainsTest, GenericContains) {
  15. constexpr char allowed_chars[] = {'a', 'b', 'c', 'd'};
  16. static_assert(Contains(allowed_chars, 'a'), "");
  17. static_assert(!Contains(allowed_chars, 'z'), "");
  18. static_assert(!Contains(allowed_chars, 0), "");
  19. constexpr char allowed_chars_including_nul[] = "abcd";
  20. static_assert(Contains(allowed_chars_including_nul, 0), "");
  21. }
  22. TEST(ContainsTest, GenericContainsWithProjection) {
  23. const char allowed_chars[] = {'A', 'B', 'C', 'D'};
  24. EXPECT_TRUE(Contains(allowed_chars, 'a', &ToLowerASCII<char>));
  25. EXPECT_FALSE(Contains(allowed_chars, 'z', &ToLowerASCII<char>));
  26. EXPECT_FALSE(Contains(allowed_chars, 0, &ToLowerASCII<char>));
  27. }
  28. TEST(ContainsTest, GenericSetContainsWithProjection) {
  29. constexpr StringPiece kFoo = "foo";
  30. std::set<std::string> set = {"foo", "bar", "baz"};
  31. // Opt into a linear search by explicitly providing a projection:
  32. EXPECT_TRUE(Contains(set, kFoo, identity{}));
  33. }
  34. TEST(ContainsTest, ContainsWithFindAndNpos) {
  35. std::string str = "abcd";
  36. EXPECT_TRUE(Contains(str, 'a'));
  37. EXPECT_FALSE(Contains(str, 'z'));
  38. EXPECT_FALSE(Contains(str, 0));
  39. }
  40. TEST(ContainsTest, ContainsWithFindAndEnd) {
  41. std::set<int> set = {1, 2, 3, 4};
  42. EXPECT_TRUE(Contains(set, 1));
  43. EXPECT_FALSE(Contains(set, 5));
  44. EXPECT_FALSE(Contains(set, 0));
  45. }
  46. TEST(ContainsTest, ContainsWithContains) {
  47. flat_set<int> set = {1, 2, 3, 4};
  48. EXPECT_TRUE(Contains(set, 1));
  49. EXPECT_FALSE(Contains(set, 5));
  50. EXPECT_FALSE(Contains(set, 0));
  51. }
  52. } // namespace base