ConvertUTFWrapper.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. //===-- ConvertUTFWrapper.cpp - Wrap ConvertUTF.h with clang data types -----===
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "llvm/ADT/ArrayRef.h"
  9. #include "llvm/ADT/StringRef.h"
  10. #include "llvm/Support/ConvertUTF.h"
  11. #include "llvm/Support/ErrorHandling.h"
  12. #include "llvm/Support/SwapByteOrder.h"
  13. #include <string>
  14. #include <vector>
  15. namespace llvm {
  16. bool ConvertUTF8toWide(unsigned WideCharWidth, llvm::StringRef Source,
  17. char *&ResultPtr, const UTF8 *&ErrorPtr) {
  18. assert(WideCharWidth == 1 || WideCharWidth == 2 || WideCharWidth == 4);
  19. ConversionResult result = conversionOK;
  20. // Copy the character span over.
  21. if (WideCharWidth == 1) {
  22. const UTF8 *Pos = reinterpret_cast<const UTF8*>(Source.begin());
  23. if (!isLegalUTF8String(&Pos, reinterpret_cast<const UTF8*>(Source.end()))) {
  24. result = sourceIllegal;
  25. ErrorPtr = Pos;
  26. } else {
  27. memcpy(ResultPtr, Source.data(), Source.size());
  28. ResultPtr += Source.size();
  29. }
  30. } else if (WideCharWidth == 2) {
  31. const UTF8 *sourceStart = (const UTF8*)Source.data();
  32. // FIXME: Make the type of the result buffer correct instead of
  33. // using reinterpret_cast.
  34. UTF16 *targetStart = reinterpret_cast<UTF16*>(ResultPtr);
  35. ConversionFlags flags = strictConversion;
  36. result = ConvertUTF8toUTF16(
  37. &sourceStart, sourceStart + Source.size(),
  38. &targetStart, targetStart + Source.size(), flags);
  39. if (result == conversionOK)
  40. ResultPtr = reinterpret_cast<char*>(targetStart);
  41. else
  42. ErrorPtr = sourceStart;
  43. } else if (WideCharWidth == 4) {
  44. const UTF8 *sourceStart = (const UTF8*)Source.data();
  45. // FIXME: Make the type of the result buffer correct instead of
  46. // using reinterpret_cast.
  47. UTF32 *targetStart = reinterpret_cast<UTF32*>(ResultPtr);
  48. ConversionFlags flags = strictConversion;
  49. result = ConvertUTF8toUTF32(
  50. &sourceStart, sourceStart + Source.size(),
  51. &targetStart, targetStart + Source.size(), flags);
  52. if (result == conversionOK)
  53. ResultPtr = reinterpret_cast<char*>(targetStart);
  54. else
  55. ErrorPtr = sourceStart;
  56. }
  57. assert((result != targetExhausted)
  58. && "ConvertUTF8toUTFXX exhausted target buffer");
  59. return result == conversionOK;
  60. }
  61. bool ConvertCodePointToUTF8(unsigned Source, char *&ResultPtr) {
  62. const UTF32 *SourceStart = &Source;
  63. const UTF32 *SourceEnd = SourceStart + 1;
  64. UTF8 *TargetStart = reinterpret_cast<UTF8 *>(ResultPtr);
  65. UTF8 *TargetEnd = TargetStart + 4;
  66. ConversionResult CR = ConvertUTF32toUTF8(&SourceStart, SourceEnd,
  67. &TargetStart, TargetEnd,
  68. strictConversion);
  69. if (CR != conversionOK)
  70. return false;
  71. ResultPtr = reinterpret_cast<char*>(TargetStart);
  72. return true;
  73. }
  74. bool hasUTF16ByteOrderMark(ArrayRef<char> S) {
  75. return (S.size() >= 2 &&
  76. ((S[0] == '\xff' && S[1] == '\xfe') ||
  77. (S[0] == '\xfe' && S[1] == '\xff')));
  78. }
  79. bool convertUTF16ToUTF8String(ArrayRef<char> SrcBytes, std::string &Out) {
  80. assert(Out.empty());
  81. // Error out on an uneven byte count.
  82. if (SrcBytes.size() % 2)
  83. return false;
  84. // Avoid OOB by returning early on empty input.
  85. if (SrcBytes.empty())
  86. return true;
  87. const UTF16 *Src = reinterpret_cast<const UTF16 *>(SrcBytes.begin());
  88. const UTF16 *SrcEnd = reinterpret_cast<const UTF16 *>(SrcBytes.end());
  89. assert((uintptr_t)Src % sizeof(UTF16) == 0);
  90. // Byteswap if necessary.
  91. std::vector<UTF16> ByteSwapped;
  92. if (Src[0] == UNI_UTF16_BYTE_ORDER_MARK_SWAPPED) {
  93. ByteSwapped.insert(ByteSwapped.end(), Src, SrcEnd);
  94. for (UTF16 &I : ByteSwapped)
  95. I = llvm::ByteSwap_16(I);
  96. Src = &ByteSwapped[0];
  97. SrcEnd = &ByteSwapped[ByteSwapped.size() - 1] + 1;
  98. }
  99. // Skip the BOM for conversion.
  100. if (Src[0] == UNI_UTF16_BYTE_ORDER_MARK_NATIVE)
  101. Src++;
  102. // Just allocate enough space up front. We'll shrink it later. Allocate
  103. // enough that we can fit a null terminator without reallocating.
  104. Out.resize(SrcBytes.size() * UNI_MAX_UTF8_BYTES_PER_CODE_POINT + 1);
  105. UTF8 *Dst = reinterpret_cast<UTF8 *>(&Out[0]);
  106. UTF8 *DstEnd = Dst + Out.size();
  107. ConversionResult CR =
  108. ConvertUTF16toUTF8(&Src, SrcEnd, &Dst, DstEnd, strictConversion);
  109. assert(CR != targetExhausted);
  110. if (CR != conversionOK) {
  111. Out.clear();
  112. return false;
  113. }
  114. Out.resize(reinterpret_cast<char *>(Dst) - &Out[0]);
  115. Out.push_back(0);
  116. Out.pop_back();
  117. return true;
  118. }
  119. bool convertUTF16ToUTF8String(ArrayRef<UTF16> Src, std::string &Out)
  120. {
  121. return convertUTF16ToUTF8String(
  122. llvm::ArrayRef<char>(reinterpret_cast<const char *>(Src.data()),
  123. Src.size() * sizeof(UTF16)), Out);
  124. }
  125. bool convertUTF8ToUTF16String(StringRef SrcUTF8,
  126. SmallVectorImpl<UTF16> &DstUTF16) {
  127. assert(DstUTF16.empty());
  128. // Avoid OOB by returning early on empty input.
  129. if (SrcUTF8.empty()) {
  130. DstUTF16.push_back(0);
  131. DstUTF16.pop_back();
  132. return true;
  133. }
  134. const UTF8 *Src = reinterpret_cast<const UTF8 *>(SrcUTF8.begin());
  135. const UTF8 *SrcEnd = reinterpret_cast<const UTF8 *>(SrcUTF8.end());
  136. // Allocate the same number of UTF-16 code units as UTF-8 code units. Encoding
  137. // as UTF-16 should always require the same amount or less code units than the
  138. // UTF-8 encoding. Allocate one extra byte for the null terminator though,
  139. // so that someone calling DstUTF16.data() gets a null terminated string.
  140. // We resize down later so we don't have to worry that this over allocates.
  141. DstUTF16.resize(SrcUTF8.size()+1);
  142. UTF16 *Dst = &DstUTF16[0];
  143. UTF16 *DstEnd = Dst + DstUTF16.size();
  144. ConversionResult CR =
  145. ConvertUTF8toUTF16(&Src, SrcEnd, &Dst, DstEnd, strictConversion);
  146. assert(CR != targetExhausted);
  147. if (CR != conversionOK) {
  148. DstUTF16.clear();
  149. return false;
  150. }
  151. DstUTF16.resize(Dst - &DstUTF16[0]);
  152. DstUTF16.push_back(0);
  153. DstUTF16.pop_back();
  154. return true;
  155. }
  156. static_assert(sizeof(wchar_t) == 1 || sizeof(wchar_t) == 2 ||
  157. sizeof(wchar_t) == 4,
  158. "Expected wchar_t to be 1, 2, or 4 bytes");
  159. template <typename TResult>
  160. static inline bool ConvertUTF8toWideInternal(llvm::StringRef Source,
  161. TResult &Result) {
  162. // Even in the case of UTF-16, the number of bytes in a UTF-8 string is
  163. // at least as large as the number of elements in the resulting wide
  164. // string, because surrogate pairs take at least 4 bytes in UTF-8.
  165. Result.resize(Source.size() + 1);
  166. char *ResultPtr = reinterpret_cast<char *>(&Result[0]);
  167. const UTF8 *ErrorPtr;
  168. if (!ConvertUTF8toWide(sizeof(wchar_t), Source, ResultPtr, ErrorPtr)) {
  169. Result.clear();
  170. return false;
  171. }
  172. Result.resize(reinterpret_cast<wchar_t *>(ResultPtr) - &Result[0]);
  173. return true;
  174. }
  175. bool ConvertUTF8toWide(llvm::StringRef Source, std::wstring &Result) {
  176. return ConvertUTF8toWideInternal(Source, Result);
  177. }
  178. bool ConvertUTF8toWide(const char *Source, std::wstring &Result) {
  179. if (!Source) {
  180. Result.clear();
  181. return true;
  182. }
  183. return ConvertUTF8toWide(llvm::StringRef(Source), Result);
  184. }
  185. bool convertWideToUTF8(const std::wstring &Source, std::string &Result) {
  186. if (sizeof(wchar_t) == 1) {
  187. const UTF8 *Start = reinterpret_cast<const UTF8 *>(Source.data());
  188. const UTF8 *End =
  189. reinterpret_cast<const UTF8 *>(Source.data() + Source.size());
  190. if (!isLegalUTF8String(&Start, End))
  191. return false;
  192. Result.resize(Source.size());
  193. memcpy(&Result[0], Source.data(), Source.size());
  194. return true;
  195. } else if (sizeof(wchar_t) == 2) {
  196. return convertUTF16ToUTF8String(
  197. llvm::ArrayRef<UTF16>(reinterpret_cast<const UTF16 *>(Source.data()),
  198. Source.size()),
  199. Result);
  200. } else if (sizeof(wchar_t) == 4) {
  201. const UTF32 *Start = reinterpret_cast<const UTF32 *>(Source.data());
  202. const UTF32 *End =
  203. reinterpret_cast<const UTF32 *>(Source.data() + Source.size());
  204. Result.resize(UNI_MAX_UTF8_BYTES_PER_CODE_POINT * Source.size());
  205. UTF8 *ResultPtr = reinterpret_cast<UTF8 *>(&Result[0]);
  206. UTF8 *ResultEnd = reinterpret_cast<UTF8 *>(&Result[0] + Result.size());
  207. if (ConvertUTF32toUTF8(&Start, End, &ResultPtr, ResultEnd,
  208. strictConversion) == conversionOK) {
  209. Result.resize(reinterpret_cast<char *>(ResultPtr) - &Result[0]);
  210. return true;
  211. } else {
  212. Result.clear();
  213. return false;
  214. }
  215. } else {
  216. llvm_unreachable(
  217. "Control should never reach this point; see static_assert further up");
  218. }
  219. }
  220. } // end namespace llvm