1 /*
2 * Copyright (C) 2018 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "Regex.h"
18
19 namespace android {
20 namespace vintf {
21 namespace details {
22
~Regex()23 Regex::~Regex() {
24 clear();
25 }
26
clear()27 void Regex::clear() {
28 if (mImpl != nullptr) {
29 regfree(mImpl.get());
30 mImpl = nullptr;
31 }
32 }
33
compile(const std::string & pattern)34 bool Regex::compile(const std::string& pattern) {
35 clear();
36 mImpl = std::make_unique<regex_t>();
37 int status = regcomp(mImpl.get(), pattern.c_str(), REG_EXTENDED | REG_NEWLINE);
38 return status == 0;
39 }
40
matches(const std::string & s) const41 bool Regex::matches(const std::string& s) const {
42 regmatch_t match;
43 int status =
44 regexec(mImpl.get(), s.c_str(), 1 /* nmatch */, &match /* pmatch */, 0 /* flags */);
45 return status == 0 && match.rm_so == 0 && match.rm_eo >= 0 &&
46 static_cast<size_t>(match.rm_eo) == s.length();
47 }
48
49 } // namespace details
50 } // namespace vintf
51 } // namespace android
52