• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2020 The Chromium Authors
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// This is a "No Compile Test" suite.
6// https://dev.chromium.org/developers/testing/no-compile-tests
7
8#include "base/containers/contains.h"
9
10#include <set>
11
12#include "base/strings/string_piece.h"
13
14namespace base {
15
16// The following code would perform a linear search through the set which is
17// likely unexpected and not intended. This is because the expression
18// `set.find(kFoo)` is ill-formed, since there is no implimit conversion from
19// StringPiece to `std::string`. This means Contains would fall back to the
20// general purpose `base::ranges::find(set, kFoo)` linear search.
21// To fix this clients can either use a more generic comparator like std::less<>
22// (in this case `set.find()` accepts any type that is comparable to a
23// std::string), or pass an explicit projection parameter to Contains, at which
24// point it will always perform a linear search.
25void UnexpectedLinearSearch() {
26  constexpr StringPiece kFoo = "foo";
27  std::set<std::string> set = {"foo", "bar", "baz"};
28  Contains(set, kFoo);  // expected-error@*:* {{About to perform linear search on an associative container}}
29}
30
31}  // namespace base
32