blob: ca352e0e9b612a2dd21b8eb4c925c7907e9e9efa [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#include "BigBuffer.h"
18#include "Maybe.h"
19#include "StringPiece.h"
20#include "Util.h"
21
22#include <algorithm>
23#include <ostream>
24#include <string>
25#include <utils/Unicode.h>
26#include <vector>
27
28namespace aapt {
29namespace util {
30
Adam Lesinski24aad162015-04-24 19:19:30 -070031constexpr const char16_t* kSchemaAuto = u"http://schemas.android.com/apk/res-auto";
32constexpr const char16_t* kSchemaPrefix = u"http://schemas.android.com/apk/res/";
33
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080034static std::vector<std::string> splitAndTransform(const StringPiece& str, char sep,
35 const std::function<char(char)>& f) {
36 std::vector<std::string> parts;
37 const StringPiece::const_iterator end = std::end(str);
38 StringPiece::const_iterator start = std::begin(str);
39 StringPiece::const_iterator current;
40 do {
41 current = std::find(start, end, sep);
42 parts.emplace_back(str.substr(start, current).toString());
43 if (f) {
44 std::string& part = parts.back();
45 std::transform(part.begin(), part.end(), part.begin(), f);
46 }
47 start = current + 1;
48 } while (current != end);
49 return parts;
50}
51
52std::vector<std::string> split(const StringPiece& str, char sep) {
53 return splitAndTransform(str, sep, nullptr);
54}
55
56std::vector<std::string> splitAndLowercase(const StringPiece& str, char sep) {
57 return splitAndTransform(str, sep, ::tolower);
58}
59
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080060StringPiece16 trimWhitespace(const StringPiece16& str) {
61 if (str.size() == 0 || str.data() == nullptr) {
62 return str;
63 }
64
65 const char16_t* start = str.data();
66 const char16_t* end = str.data() + str.length();
67
68 while (start != end && util::isspace16(*start)) {
69 start++;
70 }
71
72 while (end != start && util::isspace16(*(end - 1))) {
73 end--;
74 }
75
76 return StringPiece16(start, end - start);
77}
78
79StringPiece16::const_iterator findNonAlphaNumericAndNotInSet(const StringPiece16& str,
80 const StringPiece16& allowedChars) {
81 const auto endIter = str.end();
82 for (auto iter = str.begin(); iter != endIter; ++iter) {
83 char16_t c = *iter;
84 if ((c >= u'a' && c <= u'z') ||
85 (c >= u'A' && c <= u'Z') ||
86 (c >= u'0' && c <= u'9')) {
87 continue;
88 }
89
90 bool match = false;
91 for (char16_t i : allowedChars) {
92 if (c == i) {
93 match = true;
94 break;
95 }
96 }
97
98 if (!match) {
99 return iter;
100 }
101 }
102 return endIter;
103}
104
Adam Lesinskia1ad4a82015-06-08 11:41:09 -0700105bool isJavaClassName(const StringPiece16& str) {
106 size_t pieces = 0;
107 for (const StringPiece16& piece : tokenize(str, u'.')) {
108 pieces++;
109 if (piece.empty()) {
110 return false;
111 }
112
113 // Can't have starting or trailing $ character.
114 if (piece.data()[0] == u'$' || piece.data()[piece.size() - 1] == u'$') {
115 return false;
116 }
117
118 if (findNonAlphaNumericAndNotInSet(piece, u"$_") != piece.end()) {
119 return false;
120 }
121 }
122 return pieces >= 2;
123}
124
125Maybe<std::u16string> getFullyQualifiedClassName(const StringPiece16& package,
126 const StringPiece16& className) {
127 if (className.empty()) {
128 return {};
129 }
130
131 if (util::isJavaClassName(className)) {
132 return className.toString();
133 }
134
135 if (package.empty()) {
136 return {};
137 }
138
139 std::u16string result(package.data(), package.size());
140 if (className.data()[0] != u'.') {
141 result += u'.';
142 }
143 result.append(className.data(), className.size());
144 if (!isJavaClassName(result)) {
145 return {};
146 }
147 return result;
148}
149
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800150static Maybe<char16_t> parseUnicodeCodepoint(const char16_t** start, const char16_t* end) {
151 char16_t code = 0;
152 for (size_t i = 0; i < 4 && *start != end; i++, (*start)++) {
153 char16_t c = **start;
154 int a;
155 if (c >= '0' && c <= '9') {
156 a = c - '0';
157 } else if (c >= 'a' && c <= 'f') {
158 a = c - 'a' + 10;
159 } else if (c >= 'A' && c <= 'F') {
160 a = c - 'A' + 10;
161 } else {
162 return make_nothing<char16_t>();
163 }
164 code = (code << 4) | a;
165 }
166 return make_value(code);
167}
168
169StringBuilder& StringBuilder::append(const StringPiece16& str) {
170 if (!mError.empty()) {
171 return *this;
172 }
173
174 const char16_t* const end = str.end();
175 const char16_t* start = str.begin();
176 const char16_t* current = start;
177 while (current != end) {
Adam Lesinski90959882015-07-06 18:09:18 -0700178 if (mLastCharWasEscape) {
179 switch (*current) {
180 case u't':
181 mStr += u'\t';
182 break;
183 case u'n':
184 mStr += u'\n';
185 break;
186 case u'#':
187 mStr += u'#';
188 break;
189 case u'@':
190 mStr += u'@';
191 break;
192 case u'?':
193 mStr += u'?';
194 break;
195 case u'"':
196 mStr += u'"';
197 break;
198 case u'\'':
199 mStr += u'\'';
200 break;
201 case u'\\':
202 mStr += u'\\';
203 break;
204 case u'u': {
205 current++;
206 Maybe<char16_t> c = parseUnicodeCodepoint(&current, end);
207 if (!c) {
208 mError = "invalid unicode escape sequence";
209 return *this;
210 }
211 mStr += c.value();
212 current -= 1;
213 break;
214 }
215
216 default:
217 // Ignore.
218 break;
219 }
220 mLastCharWasEscape = false;
221 start = current + 1;
222 } else if (*current == u'"') {
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800223 if (!mQuote && mTrailingSpace) {
224 // We found an opening quote, and we have
225 // trailing space, so we should append that
226 // space now.
227 if (mTrailingSpace) {
228 // We had trailing whitespace, so
229 // replace with a single space.
230 if (!mStr.empty()) {
231 mStr += u' ';
232 }
233 mTrailingSpace = false;
234 }
235 }
236 mQuote = !mQuote;
237 mStr.append(start, current - start);
238 start = current + 1;
239 } else if (*current == u'\'' && !mQuote) {
240 // This should be escaped.
241 mError = "unescaped apostrophe";
242 return *this;
243 } else if (*current == u'\\') {
244 // This is an escape sequence, convert to the real value.
245 if (!mQuote && mTrailingSpace) {
246 // We had trailing whitespace, so
247 // replace with a single space.
248 if (!mStr.empty()) {
249 mStr += u' ';
250 }
251 mTrailingSpace = false;
252 }
253 mStr.append(start, current - start);
254 start = current + 1;
Adam Lesinski90959882015-07-06 18:09:18 -0700255 mLastCharWasEscape = true;
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800256 } else if (!mQuote) {
257 // This is not quoted text, so look for whitespace.
258 if (isspace16(*current)) {
259 // We found whitespace, see if we have seen some
260 // before.
261 if (!mTrailingSpace) {
262 // We didn't see a previous adjacent space,
263 // so mark that we did.
264 mTrailingSpace = true;
265 mStr.append(start, current - start);
266 }
267
268 // Keep skipping whitespace.
269 start = current + 1;
270 } else if (mTrailingSpace) {
271 // We saw trailing space before, so replace all
272 // that trailing space with one space.
273 if (!mStr.empty()) {
274 mStr += u' ';
275 }
276 mTrailingSpace = false;
277 }
278 }
279 current++;
280 }
281 mStr.append(start, end - start);
282 return *this;
283}
284
285std::u16string utf8ToUtf16(const StringPiece& utf8) {
286 ssize_t utf16Length = utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(utf8.data()),
287 utf8.length());
288 if (utf16Length <= 0) {
289 return {};
290 }
291
292 std::u16string utf16;
293 utf16.resize(utf16Length);
294 utf8_to_utf16(reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length(), &*utf16.begin());
295 return utf16;
296}
297
298std::string utf16ToUtf8(const StringPiece16& utf16) {
299 ssize_t utf8Length = utf16_to_utf8_length(utf16.data(), utf16.length());
300 if (utf8Length <= 0) {
301 return {};
302 }
303
304 std::string utf8;
305 utf8.resize(utf8Length);
306 utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin());
307 return utf8;
308}
309
310bool writeAll(std::ostream& out, const BigBuffer& buffer) {
311 for (const auto& b : buffer) {
312 if (!out.write(reinterpret_cast<const char*>(b.buffer.get()), b.size)) {
313 return false;
314 }
315 }
316 return true;
317}
318
319std::unique_ptr<uint8_t[]> copy(const BigBuffer& buffer) {
320 std::unique_ptr<uint8_t[]> data = std::unique_ptr<uint8_t[]>(new uint8_t[buffer.size()]);
321 uint8_t* p = data.get();
322 for (const auto& block : buffer) {
323 memcpy(p, block.buffer.get(), block.size);
324 p += block.size;
325 }
326 return data;
327}
328
Adam Lesinski24aad162015-04-24 19:19:30 -0700329Maybe<std::u16string> extractPackageFromNamespace(const std::u16string& namespaceUri) {
330 if (stringStartsWith<char16_t>(namespaceUri, kSchemaPrefix)) {
331 StringPiece16 schemaPrefix = kSchemaPrefix;
332 StringPiece16 package = namespaceUri;
333 return package.substr(schemaPrefix.size(), package.size() - schemaPrefix.size())
334 .toString();
335 } else if (namespaceUri == kSchemaAuto) {
336 return std::u16string();
337 }
338 return {};
339}
340
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800341} // namespace util
342} // namespace aapt