1 /* 2 * Copyright (C) 2016 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 "androidfw/Util.h" 18 19 #include <algorithm> 20 #include <string> 21 22 #include "utils/ByteOrder.h" 23 #include "utils/Unicode.h" 24 25 #ifdef _WIN32 26 #ifdef ERROR 27 #undef ERROR 28 #endif 29 #endif 30 31 namespace android { 32 namespace util { 33 34 void ReadUtf16StringFromDevice(const uint16_t* src, size_t len, std::string* out) { 35 char buf[5]; 36 while (*src && len != 0) { 37 char16_t c = static_cast<char16_t>(dtohs(*src)); 38 utf16_to_utf8(&c, 1, buf, sizeof(buf)); 39 out->append(buf, strlen(buf)); 40 ++src; 41 --len; 42 } 43 } 44 45 std::u16string Utf8ToUtf16(const StringPiece& utf8) { 46 ssize_t utf16_length = 47 utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length()); 48 if (utf16_length <= 0) { 49 return {}; 50 } 51 52 std::u16string utf16; 53 utf16.resize(utf16_length); 54 utf8_to_utf16(reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length(), &*utf16.begin(), 55 utf16_length + 1); 56 return utf16; 57 } 58 59 std::string Utf16ToUtf8(const StringPiece16& utf16) { 60 ssize_t utf8_length = utf16_to_utf8_length(utf16.data(), utf16.length()); 61 if (utf8_length <= 0) { 62 return {}; 63 } 64 65 std::string utf8; 66 utf8.resize(utf8_length); 67 utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin(), utf8_length + 1); 68 return utf8; 69 } 70 71 static std::vector<std::string> SplitAndTransform( 72 const StringPiece& str, char sep, const std::function<char(char)>& f) { 73 std::vector<std::string> parts; 74 const StringPiece::const_iterator end = std::end(str); 75 StringPiece::const_iterator start = std::begin(str); 76 StringPiece::const_iterator current; 77 do { 78 current = std::find(start, end, sep); 79 parts.emplace_back(str.substr(start, current).to_string()); 80 if (f) { 81 std::string& part = parts.back(); 82 std::transform(part.begin(), part.end(), part.begin(), f); 83 } 84 start = current + 1; 85 } while (current != end); 86 return parts; 87 } 88 89 std::vector<std::string> SplitAndLowercase(const StringPiece& str, char sep) { 90 return SplitAndTransform(str, sep, ::tolower); 91 } 92 93 94 } // namespace util 95 } // namespace android 96