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 "BigBuffer.h"
21 #include "Maybe.h"
22 #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 
31 namespace aapt {
32 namespace util {
33 
34 std::vector<std::string> split(const StringPiece& str, char sep);
35 std::vector<std::string> splitAndLowercase(const StringPiece& str, char sep);
36 
37 /**
38  * Returns true if the string starts with prefix.
39  */
40 template <typename T>
stringStartsWith(const BasicStringPiece<T> & str,const BasicStringPiece<T> & prefix)41 bool 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  */
51 template <typename T>
stringEndsWith(const BasicStringPiece<T> & str,const BasicStringPiece<T> & suffix)52 bool 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  */
63 StringPiece16 trimWhitespace(const StringPiece16& str);
64 
65 /**
66  * UTF-16 isspace(). It basically checks for lower range characters that are
67  * whitespace.
68  */
isspace16(char16_t c)69 inline 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  */
77 StringPiece16::const_iterator findNonAlphaNumericAndNotInSet(const StringPiece16& str,
78         const StringPiece16& allowedChars);
79 
80 /**
81  * Tests that the string is a valid Java class name.
82  */
83 bool 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  */
93 Maybe<std::u16string> getFullyQualifiedClassName(const StringPiece16& package,
94                                                  const StringPiece16& className);
95 
96 
97 /**
98  * 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  */
101 template <typename T, class... Args>
make_unique(Args &&...args)102 std::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  */
110 template <typename Iterator>
joiner(Iterator begin,Iterator end,const char * sep)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 
formatSize(size_t size)124 inline ::std::function<::std::ostream&(::std::ostream&)> formatSize(size_t size) {
125     return [size](::std::ostream& out) -> ::std::ostream& {
126         constexpr size_t K = 1024u;
127         constexpr size_t M = K * K;
128         constexpr size_t G = M * K;
129         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  */
getString(const android::ResStringPool & pool,size_t idx)145 inline 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 
154 class StringBuilder {
155 public:
156     StringBuilder& append(const StringPiece16& str);
157     const std::u16string& str() const;
158     const std::string& error() const;
159     operator bool() const;
160 
161 private:
162     std::u16string mStr;
163     bool mQuote = false;
164     bool mTrailingSpace = false;
165     std::string mError;
166 };
167 
str()168 inline const std::u16string& StringBuilder::str() const {
169     return mStr;
170 }
171 
error()172 inline const std::string& StringBuilder::error() const {
173     return mError;
174 }
175 
176 inline StringBuilder::operator bool() const {
177     return mError.empty();
178 }
179 
180 /**
181  * Converts a UTF8 string to a UTF16 string.
182  */
183 std::u16string utf8ToUtf16(const StringPiece& utf8);
184 std::string utf16ToUtf8(const StringPiece16& utf8);
185 
186 /**
187  * Writes the entire BigBuffer to the output stream.
188  */
189 bool writeAll(std::ostream& out, const BigBuffer& buffer);
190 
191 /*
192  * Copies the entire BigBuffer into a single buffer.
193  */
194 std::unique_ptr<uint8_t[]> copy(const BigBuffer& buffer);
195 
196 /**
197  * A Tokenizer implemented as an iterable collection. It does not allocate
198  * any memory on the heap nor use standard containers.
199  */
200 template <typename Char>
201 class Tokenizer {
202 public:
203     class iterator {
204     public:
205         iterator(const iterator&) = default;
206         iterator& operator=(const iterator&) = default;
207 
208         iterator& operator++();
209         BasicStringPiece<Char> operator*();
210         bool operator==(const iterator& rhs) const;
211         bool operator!=(const iterator& rhs) const;
212 
213     private:
214         friend class Tokenizer<Char>;
215 
216         iterator(BasicStringPiece<Char> s, Char sep, BasicStringPiece<Char> tok);
217 
218         BasicStringPiece<Char> str;
219         Char separator;
220         BasicStringPiece<Char> token;
221     };
222 
223     Tokenizer(BasicStringPiece<Char> str, Char sep);
224     iterator begin();
225     iterator end();
226 
227 private:
228     const iterator mBegin;
229     const iterator mEnd;
230 };
231 
232 template <typename Char>
tokenize(BasicStringPiece<Char> str,Char sep)233 inline Tokenizer<Char> tokenize(BasicStringPiece<Char> str, Char sep) {
234     return Tokenizer<Char>(str, sep);
235 }
236 
237 template <typename Char>
238 typename Tokenizer<Char>::iterator& Tokenizer<Char>::iterator::operator++() {
239     const Char* start = token.end();
240     const Char* end = str.end();
241     if (start == end) {
242         token.assign(token.end(), 0);
243         return *this;
244     }
245 
246     start += 1;
247     const Char* current = start;
248     while (current != end) {
249         if (*current == separator) {
250             token.assign(start, current - start);
251             return *this;
252         }
253         ++current;
254     }
255     token.assign(start, end - start);
256     return *this;
257 }
258 
259 template <typename Char>
260 inline BasicStringPiece<Char> Tokenizer<Char>::iterator::operator*() {
261     return token;
262 }
263 
264 template <typename Char>
265 inline bool Tokenizer<Char>::iterator::operator==(const iterator& rhs) const {
266     // We check equality here a bit differently.
267     // We need to know that the addresses are the same.
268     return token.begin() == rhs.token.begin() && token.end() == rhs.token.end();
269 }
270 
271 template <typename Char>
272 inline bool Tokenizer<Char>::iterator::operator!=(const iterator& rhs) const {
273     return !(*this == rhs);
274 }
275 
276 template <typename Char>
iterator(BasicStringPiece<Char> s,Char sep,BasicStringPiece<Char> tok)277 inline Tokenizer<Char>::iterator::iterator(BasicStringPiece<Char> s, Char sep,
278                                            BasicStringPiece<Char> tok) :
279         str(s), separator(sep), token(tok) {
280 }
281 
282 template <typename Char>
begin()283 inline typename Tokenizer<Char>::iterator Tokenizer<Char>::begin() {
284     return mBegin;
285 }
286 
287 template <typename Char>
end()288 inline typename Tokenizer<Char>::iterator Tokenizer<Char>::end() {
289     return mEnd;
290 }
291 
292 template <typename Char>
Tokenizer(BasicStringPiece<Char> str,Char sep)293 inline Tokenizer<Char>::Tokenizer(BasicStringPiece<Char> str, Char sep) :
294         mBegin(++iterator(str, sep, BasicStringPiece<Char>(str.begin() - 1, 0))),
295         mEnd(str, sep, BasicStringPiece<Char>(str.end(), 0)) {
296 }
297 
298 /**
299  * Returns a package name if the namespace URI is of the form:
300  * http://schemas.android.com/apk/res/<package>
301  *
302  * Special case: if namespaceUri is http://schemas.android.com/apk/res-auto,
303  * returns an empty package name.
304  */
305 Maybe<std::u16string> extractPackageFromNamespace(const std::u16string& namespaceUri);
306 
307 } // namespace util
308 
309 /**
310  * Stream operator for functions. Calls the function with the stream as an argument.
311  * In the aapt namespace for lookup.
312  */
313 inline ::std::ostream& operator<<(::std::ostream& out,
314                                   ::std::function<::std::ostream&(::std::ostream&)> f) {
315     return f(out);
316 }
317 
318 } // namespace aapt
319 
320 #endif // AAPT_UTIL_H
321