1 /*
2 * Copyright (C) 2024 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 <log/log.h>
20
21 namespace android {
22 namespace os {
23 namespace statsd {
24
25 using std::string;
26 using std::unique_ptr;
27
Regex(regex_t impl)28 Regex::Regex(regex_t impl) : mImpl(std::move(impl)) {
29 }
30
~Regex()31 Regex::~Regex() {
32 regfree(&mImpl);
33 }
34
create(const string & pattern)35 unique_ptr<Regex> Regex::create(const string& pattern) {
36 regex_t impl;
37 int status = regcomp(&impl, pattern.c_str(), REG_EXTENDED);
38
39 if (status != 0) { // Invalid regex pattern.
40 // Calculate size of string needed to store error description.
41 size_t errBufSize = regerror(status, &impl, nullptr, 0);
42
43 // Get the error description.
44 char errBuf[errBufSize];
45 regerror(status, &impl, errBuf, errBufSize);
46
47 ALOGE("regex_error: %s, pattern: %s", errBuf, pattern.c_str());
48 regfree(&impl);
49 return nullptr;
50 } else if (impl.re_nsub > 0) {
51 ALOGE("regex_error: subexpressions are not allowed, pattern: %s", pattern.c_str());
52 regfree(&impl);
53 return nullptr;
54 } else {
55 return std::make_unique<Regex>(impl);
56 }
57 }
58
replace(string & str,const string & replacement)59 bool Regex::replace(string& str, const string& replacement) {
60 regmatch_t match;
61 int status = regexec(&mImpl, str.c_str(), 1 /* nmatch */, &match /* pmatch */, 0 /* flags */);
62
63 if (status != 0 || match.rm_so == -1) { // No match.
64 return false;
65 }
66 str.replace(match.rm_so, match.rm_eo - match.rm_so, replacement);
67 return true;
68 }
69
70 } // namespace statsd
71 } // namespace os
72 } // namespace android
73