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