• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 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 #pragma once
18 
19 #include <ctype.h>
20 
21 #include <sstream>
22 #include <string>
23 #include <string_view>
24 #include <type_traits>
25 #include <utility>
26 #include <vector>
27 
28 namespace android {
29 namespace base {
30 
31 // Splits a string into a vector of strings.
32 //
33 // The string is split at each occurrence of a character in delimiters.
34 //
35 // The empty string is not a valid delimiter list.
36 std::vector<std::string> Split(const std::string& s,
37                                const std::string& delimiters);
38 
39 // Splits a string into a vector of string tokens.
40 //
41 // The string is split at each occurrence of a character in delimiters.
42 // Coalesce runs of delimiter bytes and ignore delimiter bytes at the start or
43 // end of string. In other words, return only nonempty string tokens.
44 // Use when you don't care about recovering the original string with Join().
45 //
46 // Example:
47 //   Tokenize(" foo  bar ", " ") => {"foo", "bar"}
48 //   Join(Tokenize("  foo  bar", " "), " ") => "foo bar"
49 //
50 // The empty string is not a valid delimiter list.
51 std::vector<std::string> Tokenize(const std::string& s, const std::string& delimiters);
52 
53 namespace internal {
54 template <typename>
55 constexpr bool always_false_v = false;
56 }
57 
58 template <typename T>
Trim(T && t)59 std::string Trim(T&& t) {
60   std::string_view sv;
61   std::string s;
62   if constexpr (std::is_convertible_v<T, std::string_view>) {
63     sv = std::forward<T>(t);
64   } else if constexpr (std::is_convertible_v<T, std::string>) {
65     // The previous version of this function allowed for types which are implicitly convertible
66     // to std::string but not to std::string_view. For these types we go through std::string first
67     // here in order to retain source compatibility.
68     s = t;
69     sv = s;
70   } else {
71     static_assert(internal::always_false_v<T>,
72                   "Implicit conversion to std::string or std::string_view not possible");
73   }
74 
75   // Skip initial whitespace.
76   while (!sv.empty() && isspace(sv.front())) {
77     sv.remove_prefix(1);
78   }
79 
80   // Skip terminating whitespace.
81   while (!sv.empty() && isspace(sv.back())) {
82     sv.remove_suffix(1);
83   }
84 
85   return std::string(sv);
86 }
87 
88 // We instantiate the common cases in strings.cpp.
89 extern template std::string Trim(const char*&);
90 extern template std::string Trim(const char*&&);
91 extern template std::string Trim(const std::string&);
92 extern template std::string Trim(const std::string&&);
93 extern template std::string Trim(std::string_view&);
94 extern template std::string Trim(std::string_view&&);
95 
96 // Joins a container of things into a single string, using the given separator.
97 template <typename ContainerT, typename SeparatorT>
Join(const ContainerT & things,SeparatorT separator)98 std::string Join(const ContainerT& things, SeparatorT separator) {
99   if (things.empty()) {
100     return "";
101   }
102 
103   std::ostringstream result;
104   result << *things.begin();
105   for (auto it = std::next(things.begin()); it != things.end(); ++it) {
106     result << separator << *it;
107   }
108   return result.str();
109 }
110 
111 // We instantiate the common cases in strings.cpp.
112 extern template std::string Join(const std::vector<std::string>&, char);
113 extern template std::string Join(const std::vector<const char*>&, char);
114 extern template std::string Join(const std::vector<std::string>&, const std::string&);
115 extern template std::string Join(const std::vector<const char*>&, const std::string&);
116 
117 // Tests whether 's' starts with 'prefix'.
118 bool StartsWith(std::string_view s, std::string_view prefix);
119 bool StartsWith(std::string_view s, char prefix);
120 bool StartsWithIgnoreCase(std::string_view s, std::string_view prefix);
121 
122 // Tests whether 's' ends with 'suffix'.
123 bool EndsWith(std::string_view s, std::string_view suffix);
124 bool EndsWith(std::string_view s, char suffix);
125 bool EndsWithIgnoreCase(std::string_view s, std::string_view suffix);
126 
127 // Tests whether 'lhs' equals 'rhs', ignoring case.
128 bool EqualsIgnoreCase(std::string_view lhs, std::string_view rhs);
129 
130 // Removes `prefix` from the start of the given string and returns true (if
131 // it was present), false otherwise.
ConsumePrefix(std::string_view * s,std::string_view prefix)132 inline bool ConsumePrefix(std::string_view* s, std::string_view prefix) {
133   if (!StartsWith(*s, prefix)) return false;
134   s->remove_prefix(prefix.size());
135   return true;
136 }
137 
138 // Removes `suffix` from the end of the given string and returns true (if
139 // it was present), false otherwise.
ConsumeSuffix(std::string_view * s,std::string_view suffix)140 inline bool ConsumeSuffix(std::string_view* s, std::string_view suffix) {
141   if (!EndsWith(*s, suffix)) return false;
142   s->remove_suffix(suffix.size());
143   return true;
144 }
145 
146 // Replaces `from` with `to` in `s`, once if `all == false`, or as many times as
147 // there are matches if `all == true`.
148 [[nodiscard]] std::string StringReplace(std::string_view s, std::string_view from,
149                                         std::string_view to, bool all);
150 
151 // Converts an errno number to its error message string.
152 std::string ErrnoNumberAsString(int errnum);
153 
154 }  // namespace base
155 }  // namespace android
156