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 #ifndef AAPT_UTIL_H
18 #define AAPT_UTIL_H
19
20 #include <functional>
21 #include <memory>
22 #include <ostream>
23 #include <string>
24 #include <vector>
25
26 #include "androidfw/BigBuffer.h"
27 #include "androidfw/ResourceTypes.h"
28 #include "androidfw/StringPiece.h"
29 #include "utils/ByteOrder.h"
30
31 #ifdef _WIN32
32 // TODO(adamlesinski): remove once http://b/32447322 is resolved.
33 // utils/ByteOrder.h includes winsock2.h on WIN32,
34 // which will pull in the ERROR definition. This conflicts
35 // with android-base/logging.h, which takes care of undefining
36 // ERROR, but it gets included too early (before winsock2.h).
37 #ifdef ERROR
38 #undef ERROR
39 #endif
40 #endif
41
42 namespace aapt {
43 namespace util {
44
45 template <typename T>
46 struct Range {
47 T start;
48 T end;
49 };
50
51 std::vector<std::string> Split(android::StringPiece str, char sep);
52 std::vector<std::string> SplitAndLowercase(android::StringPiece str, char sep);
53
54 // Returns true if the string starts with prefix.
55 bool StartsWith(android::StringPiece str, android::StringPiece prefix);
56
57 // Returns true if the string ends with suffix.
58 bool EndsWith(android::StringPiece str, android::StringPiece suffix);
59
60 // Creates a new StringPiece that points to a substring of the original string without leading
61 // whitespace.
62 android::StringPiece TrimLeadingWhitespace(android::StringPiece str);
63
64 // Creates a new StringPiece that points to a substring of the original string without trailing
65 // whitespace.
66 android::StringPiece TrimTrailingWhitespace(android::StringPiece str);
67
68 // Creates a new StringPiece that points to a substring of the original string without leading or
69 // trailing whitespace.
70 android::StringPiece TrimWhitespace(android::StringPiece str);
71
72 // Tests that the string is a valid Java class name.
73 bool IsJavaClassName(android::StringPiece str);
74
75 // Tests that the string is a valid Java package name.
76 bool IsJavaPackageName(android::StringPiece str);
77
78 // Tests that the string is a valid Android package name. More strict than a Java package name.
79 // - First character of each component (separated by '.') must be an ASCII letter.
80 // - Subsequent characters of a component can be ASCII alphanumeric or an underscore.
81 // - Package must contain at least two components, unless it is 'android'.
82 // - The maximum package name length is 223.
83 bool IsAndroidPackageName(android::StringPiece str);
84
85 // Tests that the string is a valid Android split name.
86 // - First character of each component (separated by '.') must be an ASCII letter.
87 // - Subsequent characters of a component can be ASCII alphanumeric or an underscore.
88 bool IsAndroidSplitName(android::StringPiece str);
89
90 // Tests that the string is a valid Android shared user id.
91 // - First character of each component (separated by '.') must be an ASCII letter.
92 // - Subsequent characters of a component can be ASCII alphanumeric or an underscore.
93 // - Must contain at least two components, unless package name is 'android'.
94 // - The maximum shared user id length is 223.
95 // - Treat empty string as valid, it's the case of no shared user id.
96 bool IsAndroidSharedUserId(android::StringPiece package_name, android::StringPiece shared_user_id);
97
98 // Converts the class name to a fully qualified class name from the given
99 // `package`. Ex:
100 //
101 // asdf --> package.asdf
102 // .asdf --> package.asdf
103 // .a.b --> package.a.b
104 // asdf.adsf --> asdf.adsf
105 std::optional<std::string> GetFullyQualifiedClassName(android::StringPiece package,
106 android::StringPiece class_name);
107
108 // Retrieves the formatted name of aapt2.
109 const char* GetToolName();
110
111 // Retrieves the build fingerprint of aapt2.
112 std::string GetToolFingerprint();
113
114 template <std::integral T>
compare(T a,T b)115 int compare(T a, T b) {
116 if (a < b) {
117 return -1;
118 } else if (a > b) {
119 return 1;
120 }
121 return 0;
122 }
123
124 // Makes a std::unique_ptr<> with the template parameter inferred by the compiler.
125 // This will be present in C++14 and can be removed then.
126 using std::make_unique;
127
128 // Writes a set of items to the std::ostream, joining the times with the provided separator.
129 template <typename Container>
Joiner(const Container & container,const char * sep)130 ::std::function<::std::ostream&(::std::ostream&)> Joiner(const Container& container,
131 const char* sep) {
132 using std::begin;
133 using std::end;
134 const auto begin_iter = begin(container);
135 const auto end_iter = end(container);
136 return [begin_iter, end_iter, sep](::std::ostream& out) -> ::std::ostream& {
137 for (auto iter = begin_iter; iter != end_iter; ++iter) {
138 if (iter != begin_iter) {
139 out << sep;
140 }
141 out << *iter;
142 }
143 return out;
144 };
145 }
146
147 // Checks that the Java string format contains no non-positional arguments (arguments without
148 // explicitly specifying an index) when there are more than one argument. This is an error
149 // because translations may rearrange the order of the arguments in the string, which will
150 // break the string interpolation.
151 bool VerifyJavaStringFormat(android::StringPiece str);
152
153 bool AppendStyledString(android::StringPiece input, bool preserve_spaces, std::string* out_str,
154 std::string* out_error);
155
156 class StringBuilder {
157 public:
158 StringBuilder() = default;
159
160 StringBuilder& Append(android::StringPiece str);
161 const std::string& ToString() const;
162 const std::string& Error() const;
163 bool IsEmpty() const;
164
165 // When building StyledStrings, we need UTF-16 indices into the string,
166 // which is what the Java layer expects when dealing with java
167 // String.charAt().
168 size_t Utf16Len() const;
169
170 explicit operator bool() const;
171
172 private:
173 std::string str_;
174 size_t utf16_len_ = 0;
175 bool quote_ = false;
176 bool trailing_space_ = false;
177 bool last_char_was_escape_ = false;
178 std::string error_;
179 };
180
ToString()181 inline const std::string& StringBuilder::ToString() const {
182 return str_;
183 }
184
Error()185 inline const std::string& StringBuilder::Error() const {
186 return error_;
187 }
188
IsEmpty()189 inline bool StringBuilder::IsEmpty() const {
190 return str_.empty();
191 }
192
Utf16Len()193 inline size_t StringBuilder::Utf16Len() const {
194 return utf16_len_;
195 }
196
197 inline StringBuilder::operator bool() const {
198 return error_.empty();
199 }
200
201 // Writes the entire BigBuffer to the output stream.
202 bool WriteAll(std::ostream& out, const android::BigBuffer& buffer);
203
204 // A Tokenizer implemented as an iterable collection. It does not allocate any memory on the heap
205 // nor use standard containers.
206 class Tokenizer {
207 public:
208 class iterator {
209 public:
210 using reference = android::StringPiece&;
211 using value_type = android::StringPiece;
212 using difference_type = size_t;
213 using pointer = android::StringPiece*;
214 using iterator_category = std::forward_iterator_tag;
215
216 iterator(const iterator&) = default;
217 iterator& operator=(const iterator&) = default;
218
219 iterator& operator++();
220
221 android::StringPiece operator*() { return token_; }
222 bool operator==(const iterator& rhs) const;
223 bool operator!=(const iterator& rhs) const;
224
225 private:
226 friend class Tokenizer;
227
228 iterator(android::StringPiece s, char sep, android::StringPiece tok, bool end);
229
230 android::StringPiece str_;
231 char separator_;
232 android::StringPiece token_;
233 bool end_;
234 };
235
236 Tokenizer(android::StringPiece str, char sep);
237
begin()238 iterator begin() const {
239 return begin_;
240 }
241
end()242 iterator end() const {
243 return end_;
244 }
245
246 private:
247 const iterator begin_;
248 const iterator end_;
249 };
250
Tokenize(android::StringPiece str,char sep)251 inline Tokenizer Tokenize(android::StringPiece str, char sep) {
252 return Tokenizer(str, sep);
253 }
254
255 // Given a path like: res/xml-sw600dp/foo.xml
256 //
257 // Extracts "res/xml-sw600dp/" into outPrefix.
258 // Extracts "foo" into outEntry.
259 // Extracts ".xml" into outSuffix.
260 //
261 // Returns true if successful.
262 bool ExtractResFilePathParts(android::StringPiece path, android::StringPiece* out_prefix,
263 android::StringPiece* out_entry, android::StringPiece* out_suffix);
264
265 } // namespace util
266
267 } // namespace aapt
268
269 namespace std {
270 // Stream operator for functions. Calls the function with the stream as an argument.
271 // In the aapt namespace for lookup.
272 inline ::std::ostream& operator<<(::std::ostream& out,
273 const ::std::function<::std::ostream&(::std::ostream&)>& f) {
274 return f(out);
275 }
276 } // namespace std
277
278 #endif // AAPT_UTIL_H
279