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 #include <memory>
20
21 namespace android {
22 namespace vintf {
23 namespace details {
24
~Regex()25 Regex::~Regex() {
26 clear();
27 }
28
clear()29 void Regex::clear() {
30 if (mImpl != nullptr) {
31 regfree(mImpl.get());
32 mImpl = nullptr;
33 }
34 }
35
compile(const std::string & pattern)36 bool Regex::compile(const std::string& pattern) {
37 clear();
38 mImpl = std::make_unique<regex_t>();
39 int status = regcomp(mImpl.get(), pattern.c_str(), REG_EXTENDED | REG_NEWLINE);
40 return status == 0;
41 }
42
matches(const std::string & s) const43 bool Regex::matches(const std::string& s) const {
44 regmatch_t match;
45 int status =
46 regexec(mImpl.get(), s.c_str(), 1 /* nmatch */, &match /* pmatch */, 0 /* flags */);
47 return status == 0 && match.rm_so == 0 && match.rm_eo >= 0 &&
48 static_cast<size_t>(match.rm_eo) == s.length();
49 }
50
51 } // namespace details
52 } // namespace vintf
53 } // namespace android
54