blob: 7ec6b030fd85bb60de9a12376206435fe271d67f [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
20#include "BigBuffer.h"
Adam Lesinski24aad162015-04-24 19:19:30 -070021#include "Maybe.h"
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080022#include "StringPiece.h"
23
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/**
86 * Converts the class name to a fully qualified class name from the given `package`. Ex:
87 *
88 * asdf --> package.asdf
89 * .asdf --> package.asdf
90 * .a.b --> package.a.b
91 * asdf.adsf --> asdf.adsf
92 */
93Maybe<std::u16string> getFullyQualifiedClassName(const StringPiece16& package,
94 const StringPiece16& className);
95
96
97/**
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080098 * Makes a std::unique_ptr<> with the template parameter inferred by the compiler.
99 * This will be present in C++14 and can be removed then.
100 */
101template <typename T, class... Args>
102std::unique_ptr<T> make_unique(Args&&... args) {
103 return std::unique_ptr<T>(new T{std::forward<Args>(args)...});
104}
105
106/**
107 * Writes a set of items to the std::ostream, joining the times with the provided
108 * separator.
109 */
110template <typename Iterator>
111::std::function<::std::ostream&(::std::ostream&)> joiner(Iterator begin, Iterator end,
112 const char* sep) {
113 return [begin, end, sep](::std::ostream& out) -> ::std::ostream& {
114 for (auto iter = begin; iter != end; ++iter) {
115 if (iter != begin) {
116 out << sep;
117 }
118 out << *iter;
119 }
120 return out;
121 };
122}
123
124inline ::std::function<::std::ostream&(::std::ostream&)> formatSize(size_t size) {
125 return [size](::std::ostream& out) -> ::std::ostream& {
Adam Lesinskica2fc352015-04-03 12:08:26 -0700126 constexpr size_t K = 1024u;
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800127 constexpr size_t M = K * K;
Greg Hackmann1fce4f92015-04-02 20:23:22 -0700128 constexpr size_t G = M * K;
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800129 if (size < K) {
130 out << size << "B";
131 } else if (size < M) {
132 out << (double(size) / K) << " KiB";
133 } else if (size < G) {
134 out << (double(size) / M) << " MiB";
135 } else {
136 out << (double(size) / G) << " GiB";
137 }
138 return out;
139 };
140}
141
142/**
143 * Helper method to extract a string from a StringPool.
144 */
145inline StringPiece16 getString(const android::ResStringPool& pool, size_t idx) {
146 size_t len;
147 const char16_t* str = pool.stringAt(idx, &len);
148 if (str != nullptr) {
149 return StringPiece16(str, len);
150 }
151 return StringPiece16();
152}
153
154class StringBuilder {
155public:
156 StringBuilder& append(const StringPiece16& str);
157 const std::u16string& str() const;
158 const std::string& error() const;
159 operator bool() const;
160
161private:
162 std::u16string mStr;
163 bool mQuote = false;
164 bool mTrailingSpace = false;
Adam Lesinski90959882015-07-06 18:09:18 -0700165 bool mLastCharWasEscape = false;
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800166 std::string mError;
167};
168
169inline const std::u16string& StringBuilder::str() const {
170 return mStr;
171}
172
173inline const std::string& StringBuilder::error() const {
174 return mError;
175}
176
177inline StringBuilder::operator bool() const {
178 return mError.empty();
179}
180
181/**
182 * Converts a UTF8 string to a UTF16 string.
183 */
184std::u16string utf8ToUtf16(const StringPiece& utf8);
185std::string utf16ToUtf8(const StringPiece16& utf8);
186
187/**
188 * Writes the entire BigBuffer to the output stream.
189 */
190bool writeAll(std::ostream& out, const BigBuffer& buffer);
191
192/*
193 * Copies the entire BigBuffer into a single buffer.
194 */
195std::unique_ptr<uint8_t[]> copy(const BigBuffer& buffer);
196
197/**
198 * A Tokenizer implemented as an iterable collection. It does not allocate
199 * any memory on the heap nor use standard containers.
200 */
201template <typename Char>
202class Tokenizer {
203public:
204 class iterator {
205 public:
206 iterator(const iterator&) = default;
207 iterator& operator=(const iterator&) = default;
208
209 iterator& operator++();
210 BasicStringPiece<Char> operator*();
211 bool operator==(const iterator& rhs) const;
212 bool operator!=(const iterator& rhs) const;
213
214 private:
215 friend class Tokenizer<Char>;
216
217 iterator(BasicStringPiece<Char> s, Char sep, BasicStringPiece<Char> tok);
218
219 BasicStringPiece<Char> str;
220 Char separator;
221 BasicStringPiece<Char> token;
222 };
223
224 Tokenizer(BasicStringPiece<Char> str, Char sep);
225 iterator begin();
226 iterator end();
227
228private:
229 const iterator mBegin;
230 const iterator mEnd;
231};
232
233template <typename Char>
234inline Tokenizer<Char> tokenize(BasicStringPiece<Char> str, Char sep) {
235 return Tokenizer<Char>(str, sep);
236}
237
238template <typename Char>
239typename Tokenizer<Char>::iterator& Tokenizer<Char>::iterator::operator++() {
240 const Char* start = token.end();
241 const Char* end = str.end();
242 if (start == end) {
243 token.assign(token.end(), 0);
244 return *this;
245 }
246
247 start += 1;
248 const Char* current = start;
249 while (current != end) {
250 if (*current == separator) {
251 token.assign(start, current - start);
252 return *this;
253 }
254 ++current;
255 }
256 token.assign(start, end - start);
257 return *this;
258}
259
260template <typename Char>
261inline BasicStringPiece<Char> Tokenizer<Char>::iterator::operator*() {
262 return token;
263}
264
265template <typename Char>
266inline bool Tokenizer<Char>::iterator::operator==(const iterator& rhs) const {
267 // We check equality here a bit differently.
268 // We need to know that the addresses are the same.
269 return token.begin() == rhs.token.begin() && token.end() == rhs.token.end();
270}
271
272template <typename Char>
273inline bool Tokenizer<Char>::iterator::operator!=(const iterator& rhs) const {
274 return !(*this == rhs);
275}
276
277template <typename Char>
278inline Tokenizer<Char>::iterator::iterator(BasicStringPiece<Char> s, Char sep,
279 BasicStringPiece<Char> tok) :
280 str(s), separator(sep), token(tok) {
281}
282
283template <typename Char>
284inline typename Tokenizer<Char>::iterator Tokenizer<Char>::begin() {
285 return mBegin;
286}
287
288template <typename Char>
289inline typename Tokenizer<Char>::iterator Tokenizer<Char>::end() {
290 return mEnd;
291}
292
293template <typename Char>
294inline Tokenizer<Char>::Tokenizer(BasicStringPiece<Char> str, Char sep) :
295 mBegin(++iterator(str, sep, BasicStringPiece<Char>(str.begin() - 1, 0))),
296 mEnd(str, sep, BasicStringPiece<Char>(str.end(), 0)) {
297}
298
Adam Lesinski24aad162015-04-24 19:19:30 -0700299/**
300 * Returns a package name if the namespace URI is of the form:
301 * http://schemas.android.com/apk/res/<package>
302 *
303 * Special case: if namespaceUri is http://schemas.android.com/apk/res-auto,
304 * returns an empty package name.
305 */
306Maybe<std::u16string> extractPackageFromNamespace(const std::u16string& namespaceUri);
307
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800308} // namespace util
309
310/**
311 * Stream operator for functions. Calls the function with the stream as an argument.
312 * In the aapt namespace for lookup.
313 */
314inline ::std::ostream& operator<<(::std::ostream& out,
315 ::std::function<::std::ostream&(::std::ostream&)> f) {
316 return f(out);
317}
318
319} // namespace aapt
320
321#endif // AAPT_UTIL_H