xref: /aosp_15_r20/external/icing/icing/testing/icu-i18n-test-utils.cc (revision 8b6cd535a057e39b3b86660c4aa06c99747c2136)
1 // Copyright (C) 2019 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "icing/testing/icu-i18n-test-utils.h"
16 
17 #include <cstdint>
18 #include <string>
19 
20 #include "icing/util/logging.h"
21 #include "unicode/umachine.h"
22 #include "unicode/utf8.h"
23 
24 namespace icing {
25 namespace lib {
26 
UCharToString(UChar32 uchar)27 std::string UCharToString(UChar32 uchar) {
28   std::string result;
29   uint8_t utf8_buffer[4];  // U8_APPEND writes 0 to 4 bytes
30 
31   int utf8_index = 0;
32   UBool has_error = false;
33 
34   // utf8_index is advanced to the end of the contents if successful
35   U8_APPEND(utf8_buffer, utf8_index, sizeof(utf8_buffer), uchar, has_error);
36 
37   if (has_error) {
38     ICING_VLOG(1) << "Error converting UChar32 to UTF8";
39     return "";
40   }
41   result.append(reinterpret_cast<char*>(utf8_buffer), utf8_index);
42   return result;
43 }
44 
45 }  // namespace lib
46 }  // namespace icing
47