| OLD | NEW |
| (Empty) |
| 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. | |
| 4 | |
| 5 #include "components/autofill/core/common/autofill_regexes.h" | |
| 6 | |
| 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" | |
| 13 | |
| 14 namespace { | |
| 15 | |
| 16 // A singleton class that serves as a cache of compiled regex patterns. | |
| 17 class AutofillRegexes { | |
| 18 public: | |
| 19 static AutofillRegexes* GetInstance(); | |
| 20 | |
| 21 // Returns the compiled regex matcher corresponding to |pattern|. | |
| 22 icu::RegexMatcher* GetMatcher(const base::string16& pattern); | |
| 23 | |
| 24 private: | |
| 25 AutofillRegexes(); | |
| 26 ~AutofillRegexes(); | |
| 27 friend struct DefaultSingletonTraits<AutofillRegexes>; | |
| 28 | |
| 29 // Maps patterns to their corresponding regex matchers. | |
| 30 base::ScopedPtrHashMap<base::string16, icu::RegexMatcher> matchers_; | |
| 31 | |
| 32 DISALLOW_COPY_AND_ASSIGN(AutofillRegexes); | |
| 33 }; | |
| 34 | |
| 35 // static | |
| 36 AutofillRegexes* AutofillRegexes::GetInstance() { | |
| 37 return Singleton<AutofillRegexes>::get(); | |
| 38 } | |
| 39 | |
| 40 AutofillRegexes::AutofillRegexes() { | |
| 41 } | |
| 42 | |
| 43 AutofillRegexes::~AutofillRegexes() { | |
| 44 } | |
| 45 | |
| 46 icu::RegexMatcher* AutofillRegexes::GetMatcher(const base::string16& pattern) { | |
| 47 auto it = matchers_.find(pattern); | |
| 48 if (it == matchers_.end()) { | |
| 49 const icu::UnicodeString icu_pattern(pattern.data(), pattern.length()); | |
| 50 | |
| 51 UErrorCode status = U_ZERO_ERROR; | |
| 52 scoped_ptr<icu::RegexMatcher> matcher( | |
| 53 new icu::RegexMatcher(icu_pattern, UREGEX_CASE_INSENSITIVE, status)); | |
| 54 DCHECK(U_SUCCESS(status)); | |
| 55 | |
| 56 auto result = matchers_.add(pattern, matcher.Pass()); | |
| 57 DCHECK(result.second); | |
| 58 it = result.first; | |
| 59 } | |
| 60 return it->second; | |
| 61 } | |
| 62 | |
| 63 } // namespace | |
| 64 | |
| 65 namespace autofill { | |
| 66 | |
| 67 bool MatchesPattern(const base::string16& input, | |
| 68 const base::string16& pattern) { | |
| 69 icu::RegexMatcher* matcher = | |
| 70 AutofillRegexes::GetInstance()->GetMatcher(pattern); | |
| 71 icu::UnicodeString icu_input(input.data(), input.length()); | |
| 72 matcher->reset(icu_input); | |
| 73 | |
| 74 UErrorCode status = U_ZERO_ERROR; | |
| 75 UBool match = matcher->find(0, status); | |
| 76 DCHECK(U_SUCCESS(status)); | |
| 77 return match == TRUE; | |
| 78 } | |
| 79 | |
| 80 } // namespace autofill | |
| OLD | NEW |