Move StartsWith[ASCII] to base namespace.
[chromium-blink-merge.git] / components / autofill / core / common / autofill_regexes.cc
blob64de9f4a1565b488440f011732c6a2fd754d35da
1 // Copyright 2013 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.
5 #include "components/autofill/core/common/autofill_regexes.h"
7 #include "base/containers/scoped_ptr_hash_map.h"
8 #include "base/logging.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/memory/singleton.h"
11 #include "base/strings/string16.h"
12 #include "third_party/icu/source/i18n/unicode/regex.h"
14 namespace {
16 // A singleton class that serves as a cache of compiled regex patterns.
17 class AutofillRegexes {
18 public:
19 static AutofillRegexes* GetInstance();
21 // Returns the compiled regex matcher corresponding to |pattern|.
22 icu::RegexMatcher* GetMatcher(const base::string16& pattern);
24 private:
25 AutofillRegexes();
26 ~AutofillRegexes();
27 friend struct DefaultSingletonTraits<AutofillRegexes>;
29 // Maps patterns to their corresponding regex matchers.
30 base::ScopedPtrHashMap<base::string16, scoped_ptr<icu::RegexMatcher>>
31 matchers_;
33 DISALLOW_COPY_AND_ASSIGN(AutofillRegexes);
36 // static
37 AutofillRegexes* AutofillRegexes::GetInstance() {
38 return Singleton<AutofillRegexes>::get();
41 AutofillRegexes::AutofillRegexes() {
44 AutofillRegexes::~AutofillRegexes() {
47 icu::RegexMatcher* AutofillRegexes::GetMatcher(const base::string16& pattern) {
48 auto it = matchers_.find(pattern);
49 if (it == matchers_.end()) {
50 const icu::UnicodeString icu_pattern(pattern.data(), pattern.length());
52 UErrorCode status = U_ZERO_ERROR;
53 scoped_ptr<icu::RegexMatcher> matcher(
54 new icu::RegexMatcher(icu_pattern, UREGEX_CASE_INSENSITIVE, status));
55 DCHECK(U_SUCCESS(status));
57 auto result = matchers_.add(pattern, matcher.Pass());
58 DCHECK(result.second);
59 it = result.first;
61 return it->second;
64 } // namespace
66 namespace autofill {
68 bool MatchesPattern(const base::string16& input,
69 const base::string16& pattern) {
70 icu::RegexMatcher* matcher =
71 AutofillRegexes::GetInstance()->GetMatcher(pattern);
72 icu::UnicodeString icu_input(input.data(), input.length());
73 matcher->reset(icu_input);
75 UErrorCode status = U_ZERO_ERROR;
76 UBool match = matcher->find(0, status);
77 DCHECK(U_SUCCESS(status));
78 return match == TRUE;
81 } // namespace autofill