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 <string>
20 
21 #include "utils/ByteOrder.h"
22 #include "utils/Unicode.h"
23 
24 #ifdef _WIN32
25 #ifdef ERROR
26 #undef ERROR
27 #endif
28 #endif
29 
30 namespace android {
31 namespace util {
32 
ReadUtf16StringFromDevice(const uint16_t * src,size_t len,std::string * out)33 void ReadUtf16StringFromDevice(const uint16_t* src, size_t len, std::string* out) {
34   char buf[5];
35   while (*src && len != 0) {
36     char16_t c = static_cast<char16_t>(dtohs(*src));
37     utf16_to_utf8(&c, 1, buf, sizeof(buf));
38     out->append(buf, strlen(buf));
39     ++src;
40     --len;
41   }
42 }
43 
Utf8ToUtf16(const StringPiece & utf8)44 std::u16string Utf8ToUtf16(const StringPiece& utf8) {
45   ssize_t utf16_length =
46       utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length());
47   if (utf16_length <= 0) {
48     return {};
49   }
50 
51   std::u16string utf16;
52   utf16.resize(utf16_length);
53   utf8_to_utf16(reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length(), &*utf16.begin(),
54                 utf16_length + 1);
55   return utf16;
56 }
57 
Utf16ToUtf8(const StringPiece16 & utf16)58 std::string Utf16ToUtf8(const StringPiece16& utf16) {
59   ssize_t utf8_length = utf16_to_utf8_length(utf16.data(), utf16.length());
60   if (utf8_length <= 0) {
61     return {};
62   }
63 
64   std::string utf8;
65   utf8.resize(utf8_length);
66   utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin(), utf8_length + 1);
67   return utf8;
68 }
69 
70 } // namespace util
71 } // namespace android
72