blob: 402147de32b2a0f7dfbaca9e91c42a5bdfea7b22 [file] [log] [blame]
Adam Lesinski6f6ceb72014-11-14 14:48:12 -08001/*
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
Adam Lesinski1ab598f2015-08-14 14:26:04 -070020#include "util/BigBuffer.h"
21#include "util/Maybe.h"
22#include "util/StringPiece.h"
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080023
24#include <androidfw/ResourceTypes.h>
25#include <functional>
26#include <memory>
27#include <ostream>
28#include <string>
29#include <vector>
30
31namespace aapt {
32namespace util {
33
34std::vector<std::string> split(const StringPiece& str, char sep);
35std::vector<std::string> splitAndLowercase(const StringPiece& str, char sep);
36
37/**
Adam Lesinski4d3a9872015-04-09 19:53:22 -070038 * Returns true if the string starts with prefix.
39 */
40template <typename T>
41bool stringStartsWith(const BasicStringPiece<T>& str, const BasicStringPiece<T>& prefix) {
42 if (str.size() < prefix.size()) {
43 return false;
44 }
45 return str.substr(0, prefix.size()) == prefix;
46}
47
48/**
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080049 * Returns true if the string ends with suffix.
50 */
Adam Lesinski4d3a9872015-04-09 19:53:22 -070051template <typename T>
52bool stringEndsWith(const BasicStringPiece<T>& str, const BasicStringPiece<T>& suffix) {
53 if (str.size() < suffix.size()) {
54 return false;
55 }
56 return str.substr(str.size() - suffix.size(), suffix.size()) == suffix;
57}
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080058
59/**
60 * Creates a new StringPiece16 that points to a substring
61 * of the original string without leading or trailing whitespace.
62 */
63StringPiece16 trimWhitespace(const StringPiece16& str);
64
65/**
66 * UTF-16 isspace(). It basically checks for lower range characters that are
67 * whitespace.
68 */
69inline bool isspace16(char16_t c) {
70 return c < 0x0080 && isspace(c);
71}
72
73/**
74 * Returns an iterator to the first character that is not alpha-numeric and that
75 * is not in the allowedChars set.
76 */
77StringPiece16::const_iterator findNonAlphaNumericAndNotInSet(const StringPiece16& str,
78 const StringPiece16& allowedChars);
79
80/**
Adam Lesinskia1ad4a82015-06-08 11:41:09 -070081 * Tests that the string is a valid Java class name.
82 */
83bool isJavaClassName(const StringPiece16& str);
84
85/**
Adam Lesinski1ab598f2015-08-14 14:26:04 -070086 * Tests that the string is a valid Java package name.
87 */
88bool isJavaPackageName(const StringPiece16& str);
89
90/**
Adam Lesinskia1ad4a82015-06-08 11:41:09 -070091 * Converts the class name to a fully qualified class name from the given `package`. Ex:
92 *
93 * asdf --> package.asdf
94 * .asdf --> package.asdf
95 * .a.b --> package.a.b
96 * asdf.adsf --> asdf.adsf
97 */
98Maybe<std::u16string> getFullyQualifiedClassName(const StringPiece16& package,
99 const StringPiece16& className);
100
101
102/**
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800103 * Makes a std::unique_ptr<> with the template parameter inferred by the compiler.
104 * This will be present in C++14 and can be removed then.
105 */
106template <typename T, class... Args>
107std::unique_ptr<T> make_unique(Args&&... args) {
108 return std::unique_ptr<T>(new T{std::forward<Args>(args)...});
109}
110
111/**
112 * Writes a set of items to the std::ostream, joining the times with the provided
113 * separator.
114 */
115template <typename Iterator>
116::std::function<::std::ostream&(::std::ostream&)> joiner(Iterator begin, Iterator end,
117 const char* sep) {
118 return [begin, end, sep](::std::ostream& out) -> ::std::ostream& {
119 for (auto iter = begin; iter != end; ++iter) {
120 if (iter != begin) {
121 out << sep;
122 }
123 out << *iter;
124 }
125 return out;
126 };
127}
128
129inline ::std::function<::std::ostream&(::std::ostream&)> formatSize(size_t size) {
130 return [size](::std::ostream& out) -> ::std::ostream& {
Adam Lesinskica2fc352015-04-03 12:08:26 -0700131 constexpr size_t K = 1024u;
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800132 constexpr size_t M = K * K;
Greg Hackmann1fce4f92015-04-02 20:23:22 -0700133 constexpr size_t G = M * K;
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800134 if (size < K) {
135 out << size << "B";
136 } else if (size < M) {
137 out << (double(size) / K) << " KiB";
138 } else if (size < G) {
139 out << (double(size) / M) << " MiB";
140 } else {
141 out << (double(size) / G) << " GiB";
142 }
143 return out;
144 };
145}
146
147/**
148 * Helper method to extract a string from a StringPool.
149 */
150inline StringPiece16 getString(const android::ResStringPool& pool, size_t idx) {
151 size_t len;
152 const char16_t* str = pool.stringAt(idx, &len);
153 if (str != nullptr) {
154 return StringPiece16(str, len);
155 }
156 return StringPiece16();
157}
158
159class StringBuilder {
160public:
161 StringBuilder& append(const StringPiece16& str);
162 const std::u16string& str() const;
163 const std::string& error() const;
164 operator bool() const;
165
166private:
167 std::u16string mStr;
168 bool mQuote = false;
169 bool mTrailingSpace = false;
Adam Lesinski90959882015-07-06 18:09:18 -0700170 bool mLastCharWasEscape = false;
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800171 std::string mError;
172};
173
174inline const std::u16string& StringBuilder::str() const {
175 return mStr;
176}
177
178inline const std::string& StringBuilder::error() const {
179 return mError;
180}
181
182inline StringBuilder::operator bool() const {
183 return mError.empty();
184}
185
186/**
187 * Converts a UTF8 string to a UTF16 string.
188 */
189std::u16string utf8ToUtf16(const StringPiece& utf8);
190std::string utf16ToUtf8(const StringPiece16& utf8);
191
192/**
193 * Writes the entire BigBuffer to the output stream.
194 */
195bool writeAll(std::ostream& out, const BigBuffer& buffer);
196
197/*
198 * Copies the entire BigBuffer into a single buffer.
199 */
200std::unique_ptr<uint8_t[]> copy(const BigBuffer& buffer);
201
202/**
203 * A Tokenizer implemented as an iterable collection. It does not allocate
204 * any memory on the heap nor use standard containers.
205 */
206template <typename Char>
207class Tokenizer {
208public:
209 class iterator {
210 public:
211 iterator(const iterator&) = default;
212 iterator& operator=(const iterator&) = default;
213
214 iterator& operator++();
215 BasicStringPiece<Char> operator*();
216 bool operator==(const iterator& rhs) const;
217 bool operator!=(const iterator& rhs) const;
218
219 private:
220 friend class Tokenizer<Char>;
221
222 iterator(BasicStringPiece<Char> s, Char sep, BasicStringPiece<Char> tok);
223
224 BasicStringPiece<Char> str;
225 Char separator;
226 BasicStringPiece<Char> token;
227 };
228
229 Tokenizer(BasicStringPiece<Char> str, Char sep);
230 iterator begin();
231 iterator end();
232
233private:
234 const iterator mBegin;
235 const iterator mEnd;
236};
237
238template <typename Char>
239inline Tokenizer<Char> tokenize(BasicStringPiece<Char> str, Char sep) {
240 return Tokenizer<Char>(str, sep);
241}
242
243template <typename Char>
244typename Tokenizer<Char>::iterator& Tokenizer<Char>::iterator::operator++() {
245 const Char* start = token.end();
246 const Char* end = str.end();
247 if (start == end) {
248 token.assign(token.end(), 0);
249 return *this;
250 }
251
252 start += 1;
253 const Char* current = start;
254 while (current != end) {
255 if (*current == separator) {
256 token.assign(start, current - start);
257 return *this;
258 }
259 ++current;
260 }
261 token.assign(start, end - start);
262 return *this;
263}
264
265template <typename Char>
266inline BasicStringPiece<Char> Tokenizer<Char>::iterator::operator*() {
267 return token;
268}
269
270template <typename Char>
271inline bool Tokenizer<Char>::iterator::operator==(const iterator& rhs) const {
272 // We check equality here a bit differently.
273 // We need to know that the addresses are the same.
274 return token.begin() == rhs.token.begin() && token.end() == rhs.token.end();
275}
276
277template <typename Char>
278inline bool Tokenizer<Char>::iterator::operator!=(const iterator& rhs) const {
279 return !(*this == rhs);
280}
281
282template <typename Char>
283inline Tokenizer<Char>::iterator::iterator(BasicStringPiece<Char> s, Char sep,
284 BasicStringPiece<Char> tok) :
285 str(s), separator(sep), token(tok) {
286}
287
288template <typename Char>
289inline typename Tokenizer<Char>::iterator Tokenizer<Char>::begin() {
290 return mBegin;
291}
292
293template <typename Char>
294inline typename Tokenizer<Char>::iterator Tokenizer<Char>::end() {
295 return mEnd;
296}
297
298template <typename Char>
299inline Tokenizer<Char>::Tokenizer(BasicStringPiece<Char> str, Char sep) :
300 mBegin(++iterator(str, sep, BasicStringPiece<Char>(str.begin() - 1, 0))),
301 mEnd(str, sep, BasicStringPiece<Char>(str.end(), 0)) {
302}
303
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700304inline uint16_t hostToDevice16(uint16_t value) {
305 return htods(value);
306}
307
308inline uint32_t hostToDevice32(uint32_t value) {
309 return htodl(value);
310}
311
312inline uint16_t deviceToHost16(uint16_t value) {
313 return dtohs(value);
314}
315
316inline uint32_t deviceToHost32(uint32_t value) {
317 return dtohl(value);
318}
319
Adam Lesinski24aad162015-04-24 19:19:30 -0700320/**
321 * Returns a package name if the namespace URI is of the form:
322 * http://schemas.android.com/apk/res/<package>
323 *
324 * Special case: if namespaceUri is http://schemas.android.com/apk/res-auto,
325 * returns an empty package name.
326 */
327Maybe<std::u16string> extractPackageFromNamespace(const std::u16string& namespaceUri);
328
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700329/**
330 * Given a path like: res/xml-sw600dp/foo.xml
331 *
332 * Extracts "res/xml-sw600dp/" into outPrefix.
333 * Extracts "foo" into outEntry.
334 * Extracts ".xml" into outSuffix.
335 *
336 * Returns true if successful.
337 */
338bool extractResFilePathParts(const StringPiece16& path, StringPiece16* outPrefix,
339 StringPiece16* outEntry, StringPiece16* outSuffix);
340
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800341} // namespace util
342
343/**
344 * Stream operator for functions. Calls the function with the stream as an argument.
345 * In the aapt namespace for lookup.
346 */
347inline ::std::ostream& operator<<(::std::ostream& out,
348 ::std::function<::std::ostream&(::std::ostream&)> f) {
349 return f(out);
350}
351
352} // namespace aapt
353
354#endif // AAPT_UTIL_H