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/ResourceTypes.h"
27 #include "androidfw/StringPiece.h"
28 #include "utils/ByteOrder.h"
29
30 #include "util/BigBuffer.h"
31 #include "util/Maybe.h"
32
33 #ifdef _WIN32
34 // TODO(adamlesinski): remove once http://b/32447322 is resolved.
35 // utils/ByteOrder.h includes winsock2.h on WIN32,
36 // which will pull in the ERROR definition. This conflicts
37 // with android-base/logging.h, which takes care of undefining
38 // ERROR, but it gets included too early (before winsock2.h).
39 #ifdef ERROR
40 #undef ERROR
41 #endif
42 #endif
43
44 namespace aapt {
45 namespace util {
46
47 template <typename T>
48 struct Range {
49 T start;
50 T end;
51 };
52
53 std::vector<std::string> Split(const android::StringPiece& str, char sep);
54 std::vector<std::string> SplitAndLowercase(const android::StringPiece& str, char sep);
55
56 /**
57 * Returns true if the string starts with prefix.
58 */
59 bool StartsWith(const android::StringPiece& str, const android::StringPiece& prefix);
60
61 /**
62 * Returns true if the string ends with suffix.
63 */
64 bool EndsWith(const android::StringPiece& str, const android::StringPiece& suffix);
65
66 /**
67 * Creates a new StringPiece16 that points to a substring
68 * of the original string without leading or trailing whitespace.
69 */
70 android::StringPiece TrimWhitespace(const android::StringPiece& str);
71
72 /**
73 * Returns an iterator to the first character that is not alpha-numeric and that
74 * is not in the allowedChars set.
75 */
76 android::StringPiece::const_iterator FindNonAlphaNumericAndNotInSet(
77 const android::StringPiece& str, const android::StringPiece& allowed_chars);
78
79 /**
80 * Tests that the string is a valid Java class name.
81 */
82 bool IsJavaClassName(const android::StringPiece& str);
83
84 /**
85 * Tests that the string is a valid Java package name.
86 */
87 bool IsJavaPackageName(const android::StringPiece& str);
88
89 /**
90 * Converts the class name to a fully qualified class name from the given
91 * `package`. Ex:
92 *
93 * asdf --> package.asdf
94 * .asdf --> package.asdf
95 * .a.b --> package.a.b
96 * asdf.adsf --> asdf.adsf
97 */
98 Maybe<std::string> GetFullyQualifiedClassName(const android::StringPiece& package,
99 const android::StringPiece& class_name);
100
101 template <typename T>
compare(const T & a,const T & b)102 typename std::enable_if<std::is_arithmetic<T>::value, int>::type compare(const T& a, const T& b) {
103 if (a < b) {
104 return -1;
105 } else if (a > b) {
106 return 1;
107 }
108 return 0;
109 }
110
111 /**
112 * Makes a std::unique_ptr<> with the template parameter inferred by the compiler.
113 * This will be present in C++14 and can be removed then.
114 */
115 template <typename T, class... Args>
make_unique(Args &&...args)116 std::unique_ptr<T> make_unique(Args&&... args) {
117 return std::unique_ptr<T>(new T{std::forward<Args>(args)...});
118 }
119
120 /**
121 * Writes a set of items to the std::ostream, joining the times with the
122 * provided
123 * separator.
124 */
125 template <typename Container>
Joiner(const Container & container,const char * sep)126 ::std::function<::std::ostream&(::std::ostream&)> Joiner(
127 const Container& container, const char* sep) {
128 using std::begin;
129 using std::end;
130 const auto begin_iter = begin(container);
131 const auto end_iter = end(container);
132 return [begin_iter, end_iter, sep](::std::ostream& out) -> ::std::ostream& {
133 for (auto iter = begin_iter; iter != end_iter; ++iter) {
134 if (iter != begin_iter) {
135 out << sep;
136 }
137 out << *iter;
138 }
139 return out;
140 };
141 }
142
143 /**
144 * Helper method to extract a UTF-16 string from a StringPool. If the string is
145 * stored as UTF-8,
146 * the conversion to UTF-16 happens within ResStringPool.
147 */
148 android::StringPiece16 GetString16(const android::ResStringPool& pool, size_t idx);
149
150 /**
151 * Helper method to extract a UTF-8 string from a StringPool. If the string is
152 * stored as UTF-16,
153 * the conversion from UTF-16 to UTF-8 does not happen in ResStringPool and is
154 * done by this method,
155 * which maintains no state or cache. This means we must return an std::string
156 * copy.
157 */
158 std::string GetString(const android::ResStringPool& pool, size_t idx);
159
160 /**
161 * Checks that the Java string format contains no non-positional arguments
162 * (arguments without
163 * explicitly specifying an index) when there are more than one argument. This
164 * is an error
165 * because translations may rearrange the order of the arguments in the string,
166 * which will
167 * break the string interpolation.
168 */
169 bool VerifyJavaStringFormat(const android::StringPiece& str);
170
171 class StringBuilder {
172 public:
173 explicit StringBuilder(bool preserve_spaces = false);
174
175 StringBuilder& Append(const android::StringPiece& str);
176 const std::string& ToString() const;
177 const std::string& Error() const;
178 bool IsEmpty() const;
179
180 // When building StyledStrings, we need UTF-16 indices into the string,
181 // which is what the Java layer expects when dealing with java
182 // String.charAt().
183 size_t Utf16Len() const;
184
185 explicit operator bool() const;
186
187 private:
188 bool preserve_spaces_;
189 std::string str_;
190 size_t utf16_len_ = 0;
191 bool quote_ = false;
192 bool trailing_space_ = false;
193 bool last_char_was_escape_ = false;
194 std::string error_;
195 };
196
ToString()197 inline const std::string& StringBuilder::ToString() const { return str_; }
198
Error()199 inline const std::string& StringBuilder::Error() const { return error_; }
200
IsEmpty()201 inline bool StringBuilder::IsEmpty() const { return str_.empty(); }
202
Utf16Len()203 inline size_t StringBuilder::Utf16Len() const { return utf16_len_; }
204
205 inline StringBuilder::operator bool() const { return error_.empty(); }
206
207 /**
208 * Converts a UTF8 string to a UTF16 string.
209 */
210 std::u16string Utf8ToUtf16(const android::StringPiece& utf8);
211 std::string Utf16ToUtf8(const android::StringPiece16& utf16);
212
213 /**
214 * Writes the entire BigBuffer to the output stream.
215 */
216 bool WriteAll(std::ostream& out, const BigBuffer& buffer);
217
218 /*
219 * Copies the entire BigBuffer into a single buffer.
220 */
221 std::unique_ptr<uint8_t[]> Copy(const BigBuffer& buffer);
222
223 /**
224 * A Tokenizer implemented as an iterable collection. It does not allocate
225 * any memory on the heap nor use standard containers.
226 */
227 class Tokenizer {
228 public:
229 class iterator {
230 public:
231 using reference = android::StringPiece&;
232 using value_type = android::StringPiece;
233 using difference_type = size_t;
234 using pointer = android::StringPiece*;
235 using iterator_category = std::forward_iterator_tag;
236
237 iterator(const iterator&) = default;
238 iterator& operator=(const iterator&) = default;
239
240 iterator& operator++();
241
242 android::StringPiece operator*() { return token_; }
243 bool operator==(const iterator& rhs) const;
244 bool operator!=(const iterator& rhs) const;
245
246 private:
247 friend class Tokenizer;
248
249 iterator(android::StringPiece s, char sep, android::StringPiece tok, bool end);
250
251 android::StringPiece str_;
252 char separator_;
253 android::StringPiece token_;
254 bool end_;
255 };
256
257 Tokenizer(android::StringPiece str, char sep);
258
begin()259 iterator begin() const {
260 return begin_;
261 }
262
end()263 iterator end() const {
264 return end_;
265 }
266
267 private:
268 const iterator begin_;
269 const iterator end_;
270 };
271
Tokenize(const android::StringPiece & str,char sep)272 inline Tokenizer Tokenize(const android::StringPiece& str, char sep) { return Tokenizer(str, sep); }
273
HostToDevice16(uint16_t value)274 inline uint16_t HostToDevice16(uint16_t value) { return htods(value); }
275
HostToDevice32(uint32_t value)276 inline uint32_t HostToDevice32(uint32_t value) { return htodl(value); }
277
DeviceToHost16(uint16_t value)278 inline uint16_t DeviceToHost16(uint16_t value) { return dtohs(value); }
279
DeviceToHost32(uint32_t value)280 inline uint32_t DeviceToHost32(uint32_t value) { return dtohl(value); }
281
282 /**
283 * Given a path like: res/xml-sw600dp/foo.xml
284 *
285 * Extracts "res/xml-sw600dp/" into outPrefix.
286 * Extracts "foo" into outEntry.
287 * Extracts ".xml" into outSuffix.
288 *
289 * Returns true if successful.
290 */
291 bool ExtractResFilePathParts(const android::StringPiece& path, android::StringPiece* out_prefix,
292 android::StringPiece* out_entry, android::StringPiece* out_suffix);
293
294 } // namespace util
295
296 /**
297 * Stream operator for functions. Calls the function with the stream as an
298 * argument.
299 * In the aapt namespace for lookup.
300 */
301 inline ::std::ostream& operator<<(
302 ::std::ostream& out,
303 const ::std::function<::std::ostream&(::std::ostream&)>& f) {
304 return f(out);
305 }
306
307 } // namespace aapt
308
309 #endif // AAPT_UTIL_H
310