xref: /aosp_15_r20/system/linkerconfig/modules/stringutil.cc (revision e5eeaa8e05bc25a862c0c861bda7c8a6bfb42dad)
1 /*
2  * Copyright (C) 2020 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 #include "linkerconfig/stringutil.h"
17 
18 #include <type_traits>
19 #include <unordered_set>
20 #include <vector>
21 
22 #include <android-base/strings.h>
23 
24 namespace android {
25 namespace linkerconfig {
26 namespace modules {
TrimPrefix(const std::string & s,const std::string & prefix)27 std::string TrimPrefix(const std::string& s, const std::string& prefix) {
28   if (android::base::StartsWith(s, prefix)) {
29     return s.substr(prefix.size());
30   }
31   return s;
32 }
33 
34 // merge a list of libs into a single value (concat with ":")
MergeLibs(const std::vector<std::string> & libs)35 std::string MergeLibs(const std::vector<std::string>& libs) {
36   std::unordered_set<std::string_view> seen;
37   std::string out;
38   bool first = true;
39   for (const auto& part : libs) {
40     const char* part_str = part.c_str();
41     const char* part_end = part.c_str() + part.size();
42     while (part_str != part_end) {
43       const void* end = memchr(part_str, ':', part_end - part_str);
44       const char* end_str = end ? static_cast<const char*>(end) : part_end;
45       std::string_view lib(part_str, end_str - part_str);
46       static_assert(
47           std::is_const_v<typeof(libs)>,
48           "libs needs to be const so we can use a string_view in seen");
49       if (!lib.empty() && seen.insert(lib).second) {  // for a new lib
50         if (!first) {
51           out += ':';
52         }
53         out += lib;
54         first = false;
55       }
56       if (end == nullptr) break;
57       part_str = end_str + 1;
58     }
59   }
60   return out;
61 }
62 }  // namespace modules
63 }  // namespace linkerconfig
64 }  // namespace android