2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "util/BigBuffer.h"
18 #include "util/Maybe.h"
19 #include "util/StringPiece.h"
20 #include "util/Util.h"
25 #include <utils/Unicode.h>
31 static std::vector<std::string> splitAndTransform(const StringPiece& str, char sep,
32 const std::function<char(char)>& f) {
33 std::vector<std::string> parts;
34 const StringPiece::const_iterator end = std::end(str);
35 StringPiece::const_iterator start = std::begin(str);
36 StringPiece::const_iterator current;
38 current = std::find(start, end, sep);
39 parts.emplace_back(str.substr(start, current).toString());
41 std::string& part = parts.back();
42 std::transform(part.begin(), part.end(), part.begin(), f);
45 } while (current != end);
49 std::vector<std::string> split(const StringPiece& str, char sep) {
50 return splitAndTransform(str, sep, nullptr);
53 std::vector<std::string> splitAndLowercase(const StringPiece& str, char sep) {
54 return splitAndTransform(str, sep, ::tolower);
57 StringPiece16 trimWhitespace(const StringPiece16& str) {
58 if (str.size() == 0 || str.data() == nullptr) {
62 const char16_t* start = str.data();
63 const char16_t* end = str.data() + str.length();
65 while (start != end && util::isspace16(*start)) {
69 while (end != start && util::isspace16(*(end - 1))) {
73 return StringPiece16(start, end - start);
76 StringPiece trimWhitespace(const StringPiece& str) {
77 if (str.size() == 0 || str.data() == nullptr) {
81 const char* start = str.data();
82 const char* end = str.data() + str.length();
84 while (start != end && isspace(*start)) {
88 while (end != start && isspace(*(end - 1))) {
92 return StringPiece(start, end - start);
95 StringPiece16::const_iterator findNonAlphaNumericAndNotInSet(const StringPiece16& str,
96 const StringPiece16& allowedChars) {
97 const auto endIter = str.end();
98 for (auto iter = str.begin(); iter != endIter; ++iter) {
100 if ((c >= u'a' && c <= u'z') ||
101 (c >= u'A' && c <= u'Z') ||
102 (c >= u'0' && c <= u'9')) {
107 for (char16_t i : allowedChars) {
121 bool isJavaClassName(const StringPiece16& str) {
123 for (const StringPiece16& piece : tokenize(str, u'.')) {
129 // Can't have starting or trailing $ character.
130 if (piece.data()[0] == u'$' || piece.data()[piece.size() - 1] == u'$') {
134 if (findNonAlphaNumericAndNotInSet(piece, u"$_") != piece.end()) {
141 bool isJavaPackageName(const StringPiece16& str) {
147 for (const StringPiece16& piece : tokenize(str, u'.')) {
153 if (piece.data()[0] == u'_' || piece.data()[piece.size() - 1] == u'_') {
157 if (findNonAlphaNumericAndNotInSet(piece, u"_") != piece.end()) {
164 Maybe<std::u16string> getFullyQualifiedClassName(const StringPiece16& package,
165 const StringPiece16& className) {
166 if (className.empty()) {
170 if (util::isJavaClassName(className)) {
171 return className.toString();
174 if (package.empty()) {
178 if (className.data()[0] != u'.') {
182 std::u16string result(package.data(), package.size());
183 result.append(className.data(), className.size());
184 if (!isJavaClassName(result)) {
190 static size_t consumeDigits(const char16_t* start, const char16_t* end) {
191 const char16_t* c = start;
192 for (; c != end && *c >= u'0' && *c <= u'9'; c++) {}
193 return static_cast<size_t>(c - start);
196 bool verifyJavaStringFormat(const StringPiece16& str) {
197 const char16_t* c = str.begin();
198 const char16_t* const end = str.end();
201 bool nonpositional = false;
203 if (*c == u'%' && c + 1 < end) {
213 size_t numDigits = consumeDigits(c, end);
216 if (c != end && *c != u'$') {
217 // The digits were a size, but not a positional argument.
218 nonpositional = true;
220 } else if (*c == u'<') {
221 // Reusing last argument, bad idea since positions can be moved around
222 // during translation.
223 nonpositional = true;
227 // Optionally we can have a $ after
228 if (c != end && *c == u'$') {
232 nonpositional = true;
235 // Ignore size, width, flags, etc.
236 while (c != end && (*c == u'-' ||
242 (*c >= u'0' && *c <= '9'))) {
247 * This is a shortcut to detect strings that are going to Time.format()
248 * instead of String.format()
250 * Comparison of String.format() and Time.format() args:
252 * String: ABC E GH ST X abcdefgh nost x
253 * Time: DEFGHKMS W Za d hkm s w yz
255 * Therefore we know it's definitely Time if we have:
281 if (argCount > 1 && nonpositional) {
282 // Multiple arguments were specified, but some or all were non positional. Translated
283 // strings may rearrange the order of the arguments, which will break the string.
289 static Maybe<char16_t> parseUnicodeCodepoint(const char16_t** start, const char16_t* end) {
291 for (size_t i = 0; i < 4 && *start != end; i++, (*start)++) {
292 char16_t c = **start;
294 if (c >= '0' && c <= '9') {
296 } else if (c >= 'a' && c <= 'f') {
298 } else if (c >= 'A' && c <= 'F') {
301 return make_nothing<char16_t>();
303 code = (code << 4) | a;
305 return make_value(code);
308 StringBuilder& StringBuilder::append(const StringPiece16& str) {
309 if (!mError.empty()) {
313 const char16_t* const end = str.end();
314 const char16_t* start = str.begin();
315 const char16_t* current = start;
316 while (current != end) {
317 if (mLastCharWasEscape) {
345 Maybe<char16_t> c = parseUnicodeCodepoint(¤t, end);
347 mError = "invalid unicode escape sequence";
359 mLastCharWasEscape = false;
361 } else if (*current == u'"') {
362 if (!mQuote && mTrailingSpace) {
363 // We found an opening quote, and we have
364 // trailing space, so we should append that
366 if (mTrailingSpace) {
367 // We had trailing whitespace, so
368 // replace with a single space.
372 mTrailingSpace = false;
376 mStr.append(start, current - start);
378 } else if (*current == u'\'' && !mQuote) {
379 // This should be escaped.
380 mError = "unescaped apostrophe";
382 } else if (*current == u'\\') {
383 // This is an escape sequence, convert to the real value.
384 if (!mQuote && mTrailingSpace) {
385 // We had trailing whitespace, so
386 // replace with a single space.
390 mTrailingSpace = false;
392 mStr.append(start, current - start);
394 mLastCharWasEscape = true;
395 } else if (!mQuote) {
396 // This is not quoted text, so look for whitespace.
397 if (isspace16(*current)) {
398 // We found whitespace, see if we have seen some
400 if (!mTrailingSpace) {
401 // We didn't see a previous adjacent space,
402 // so mark that we did.
403 mTrailingSpace = true;
404 mStr.append(start, current - start);
407 // Keep skipping whitespace.
409 } else if (mTrailingSpace) {
410 // We saw trailing space before, so replace all
411 // that trailing space with one space.
415 mTrailingSpace = false;
420 mStr.append(start, end - start);
424 std::u16string utf8ToUtf16(const StringPiece& utf8) {
425 ssize_t utf16Length = utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(utf8.data()),
427 if (utf16Length <= 0) {
431 std::u16string utf16;
432 utf16.resize(utf16Length);
433 utf8_to_utf16(reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length(), &*utf16.begin());
437 std::string utf16ToUtf8(const StringPiece16& utf16) {
438 ssize_t utf8Length = utf16_to_utf8_length(utf16.data(), utf16.length());
439 if (utf8Length <= 0) {
444 // Make room for '\0' explicitly.
445 utf8.resize(utf8Length + 1);
446 utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin(), utf8Length + 1);
447 utf8.resize(utf8Length);
451 bool writeAll(std::ostream& out, const BigBuffer& buffer) {
452 for (const auto& b : buffer) {
453 if (!out.write(reinterpret_cast<const char*>(b.buffer.get()), b.size)) {
460 std::unique_ptr<uint8_t[]> copy(const BigBuffer& buffer) {
461 std::unique_ptr<uint8_t[]> data = std::unique_ptr<uint8_t[]>(new uint8_t[buffer.size()]);
462 uint8_t* p = data.get();
463 for (const auto& block : buffer) {
464 memcpy(p, block.buffer.get(), block.size);
470 bool extractResFilePathParts(const StringPiece16& path, StringPiece16* outPrefix,
471 StringPiece16* outEntry, StringPiece16* outSuffix) {
472 if (!stringStartsWith<char16_t>(path, u"res/")) {
476 StringPiece16::const_iterator lastOccurence = path.end();
477 for (auto iter = path.begin() + StringPiece16(u"res/").size(); iter != path.end(); ++iter) {
479 lastOccurence = iter;
483 if (lastOccurence == path.end()) {
487 auto iter = std::find(lastOccurence, path.end(), u'.');
488 *outSuffix = StringPiece16(iter, path.end() - iter);
489 *outEntry = StringPiece16(lastOccurence + 1, iter - lastOccurence - 1);
490 *outPrefix = StringPiece16(path.begin(), lastOccurence - path.begin() + 1);