ConvertUTFWrapper.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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 =
  37. ConvertUTF8toUTF16(&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 =
  50. ConvertUTF8toUTF32(&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(
  67. &SourceStart, SourceEnd, &TargetStart, TargetEnd, strictConversion);
  68. if (CR != conversionOK)
  69. return false;
  70. ResultPtr = reinterpret_cast<char *>(TargetStart);
  71. return true;
  72. }
  73. bool hasUTF16ByteOrderMark(ArrayRef<char> S) {
  74. return (S.size() >= 2 && ((S[0] == '\xff' && S[1] == '\xfe') ||
  75. (S[0] == '\xfe' && S[1] == '\xff')));
  76. }
  77. bool convertUTF16ToUTF8String(ArrayRef<char> SrcBytes, std::string &Out) {
  78. assert(Out.empty());
  79. // Error out on an uneven byte count.
  80. if (SrcBytes.size() % 2)
  81. return false;
  82. // Avoid OOB by returning early on empty input.
  83. if (SrcBytes.empty())
  84. return true;
  85. const UTF16 *Src = reinterpret_cast<const UTF16 *>(SrcBytes.begin());
  86. const UTF16 *SrcEnd = reinterpret_cast<const UTF16 *>(SrcBytes.end());
  87. assert((uintptr_t)Src % sizeof(UTF16) == 0);
  88. // Byteswap if necessary.
  89. std::vector<UTF16> ByteSwapped;
  90. if (Src[0] == UNI_UTF16_BYTE_ORDER_MARK_SWAPPED) {
  91. ByteSwapped.insert(ByteSwapped.end(), Src, SrcEnd);
  92. for (UTF16 &I : ByteSwapped)
  93. I = llvm::ByteSwap_16(I);
  94. Src = &ByteSwapped[0];
  95. SrcEnd = &ByteSwapped[ByteSwapped.size() - 1] + 1;
  96. }
  97. // Skip the BOM for conversion.
  98. if (Src[0] == UNI_UTF16_BYTE_ORDER_MARK_NATIVE)
  99. Src++;
  100. // Just allocate enough space up front. We'll shrink it later. Allocate
  101. // enough that we can fit a null terminator without reallocating.
  102. Out.resize(SrcBytes.size() * UNI_MAX_UTF8_BYTES_PER_CODE_POINT + 1);
  103. UTF8 *Dst = reinterpret_cast<UTF8 *>(&Out[0]);
  104. UTF8 *DstEnd = Dst + Out.size();
  105. ConversionResult CR =
  106. ConvertUTF16toUTF8(&Src, SrcEnd, &Dst, DstEnd, strictConversion);
  107. assert(CR != targetExhausted);
  108. if (CR != conversionOK) {
  109. Out.clear();
  110. return false;
  111. }
  112. Out.resize(reinterpret_cast<char *>(Dst) - &Out[0]);
  113. Out.push_back(0);
  114. Out.pop_back();
  115. return true;
  116. }
  117. bool convertUTF16ToUTF8String(ArrayRef<UTF16> Src, std::string &Out) {
  118. return convertUTF16ToUTF8String(
  119. llvm::ArrayRef<char>(reinterpret_cast<const char *>(Src.data()),
  120. Src.size() * sizeof(UTF16)),
  121. Out);
  122. }
  123. bool convertUTF32ToUTF8String(ArrayRef<char> SrcBytes, std::string &Out) {
  124. assert(Out.empty());
  125. // Error out on an uneven byte count.
  126. if (SrcBytes.size() % 4)
  127. return false;
  128. // Avoid OOB by returning early on empty input.
  129. if (SrcBytes.empty())
  130. return true;
  131. const UTF32 *Src = reinterpret_cast<const UTF32 *>(SrcBytes.begin());
  132. const UTF32 *SrcEnd = reinterpret_cast<const UTF32 *>(SrcBytes.end());
  133. assert((uintptr_t)Src % sizeof(UTF32) == 0);
  134. // Byteswap if necessary.
  135. std::vector<UTF32> ByteSwapped;
  136. if (Src[0] == UNI_UTF32_BYTE_ORDER_MARK_SWAPPED) {
  137. ByteSwapped.insert(ByteSwapped.end(), Src, SrcEnd);
  138. for (UTF32 &I : ByteSwapped)
  139. I = llvm::ByteSwap_32(I);
  140. Src = &ByteSwapped[0];
  141. SrcEnd = &ByteSwapped[ByteSwapped.size() - 1] + 1;
  142. }
  143. // Skip the BOM for conversion.
  144. if (Src[0] == UNI_UTF32_BYTE_ORDER_MARK_NATIVE)
  145. Src++;
  146. // Just allocate enough space up front. We'll shrink it later. Allocate
  147. // enough that we can fit a null terminator without reallocating.
  148. Out.resize(SrcBytes.size() * UNI_MAX_UTF8_BYTES_PER_CODE_POINT + 1);
  149. UTF8 *Dst = reinterpret_cast<UTF8 *>(&Out[0]);
  150. UTF8 *DstEnd = Dst + Out.size();
  151. ConversionResult CR =
  152. ConvertUTF32toUTF8(&Src, SrcEnd, &Dst, DstEnd, strictConversion);
  153. assert(CR != targetExhausted);
  154. if (CR != conversionOK) {
  155. Out.clear();
  156. return false;
  157. }
  158. Out.resize(reinterpret_cast<char *>(Dst) - &Out[0]);
  159. Out.push_back(0);
  160. Out.pop_back();
  161. return true;
  162. }
  163. bool convertUTF32ToUTF8String(ArrayRef<UTF32> Src, std::string &Out) {
  164. return convertUTF32ToUTF8String(
  165. llvm::ArrayRef<char>(reinterpret_cast<const char *>(Src.data()),
  166. Src.size() * sizeof(UTF32)),
  167. Out);
  168. }
  169. bool convertUTF8ToUTF16String(StringRef SrcUTF8,
  170. SmallVectorImpl<UTF16> &DstUTF16) {
  171. assert(DstUTF16.empty());
  172. // Avoid OOB by returning early on empty input.
  173. if (SrcUTF8.empty()) {
  174. DstUTF16.push_back(0);
  175. DstUTF16.pop_back();
  176. return true;
  177. }
  178. const UTF8 *Src = reinterpret_cast<const UTF8 *>(SrcUTF8.begin());
  179. const UTF8 *SrcEnd = reinterpret_cast<const UTF8 *>(SrcUTF8.end());
  180. // Allocate the same number of UTF-16 code units as UTF-8 code units. Encoding
  181. // as UTF-16 should always require the same amount or less code units than the
  182. // UTF-8 encoding. Allocate one extra byte for the null terminator though,
  183. // so that someone calling DstUTF16.data() gets a null terminated string.
  184. // We resize down later so we don't have to worry that this over allocates.
  185. DstUTF16.resize(SrcUTF8.size()+1);
  186. UTF16 *Dst = &DstUTF16[0];
  187. UTF16 *DstEnd = Dst + DstUTF16.size();
  188. ConversionResult CR =
  189. ConvertUTF8toUTF16(&Src, SrcEnd, &Dst, DstEnd, strictConversion);
  190. assert(CR != targetExhausted);
  191. if (CR != conversionOK) {
  192. DstUTF16.clear();
  193. return false;
  194. }
  195. DstUTF16.resize(Dst - &DstUTF16[0]);
  196. DstUTF16.push_back(0);
  197. DstUTF16.pop_back();
  198. return true;
  199. }
  200. static_assert(sizeof(wchar_t) == 1 || sizeof(wchar_t) == 2 ||
  201. sizeof(wchar_t) == 4,
  202. "Expected wchar_t to be 1, 2, or 4 bytes");
  203. template <typename TResult>
  204. static inline bool ConvertUTF8toWideInternal(llvm::StringRef Source,
  205. TResult &Result) {
  206. // Even in the case of UTF-16, the number of bytes in a UTF-8 string is
  207. // at least as large as the number of elements in the resulting wide
  208. // string, because surrogate pairs take at least 4 bytes in UTF-8.
  209. Result.resize(Source.size() + 1);
  210. char *ResultPtr = reinterpret_cast<char *>(&Result[0]);
  211. const UTF8 *ErrorPtr;
  212. if (!ConvertUTF8toWide(sizeof(wchar_t), Source, ResultPtr, ErrorPtr)) {
  213. Result.clear();
  214. return false;
  215. }
  216. Result.resize(reinterpret_cast<wchar_t *>(ResultPtr) - &Result[0]);
  217. return true;
  218. }
  219. bool ConvertUTF8toWide(llvm::StringRef Source, std::wstring &Result) {
  220. return ConvertUTF8toWideInternal(Source, Result);
  221. }
  222. bool ConvertUTF8toWide(const char *Source, std::wstring &Result) {
  223. if (!Source) {
  224. Result.clear();
  225. return true;
  226. }
  227. return ConvertUTF8toWide(llvm::StringRef(Source), Result);
  228. }
  229. bool convertWideToUTF8(const std::wstring &Source, std::string &Result) {
  230. if (sizeof(wchar_t) == 1) {
  231. const UTF8 *Start = reinterpret_cast<const UTF8 *>(Source.data());
  232. const UTF8 *End =
  233. reinterpret_cast<const UTF8 *>(Source.data() + Source.size());
  234. if (!isLegalUTF8String(&Start, End))
  235. return false;
  236. Result.resize(Source.size());
  237. memcpy(&Result[0], Source.data(), Source.size());
  238. return true;
  239. } else if (sizeof(wchar_t) == 2) {
  240. return convertUTF16ToUTF8String(
  241. llvm::ArrayRef<UTF16>(reinterpret_cast<const UTF16 *>(Source.data()),
  242. Source.size()),
  243. Result);
  244. } else if (sizeof(wchar_t) == 4) {
  245. const UTF32 *Start = reinterpret_cast<const UTF32 *>(Source.data());
  246. const UTF32 *End =
  247. reinterpret_cast<const UTF32 *>(Source.data() + Source.size());
  248. Result.resize(UNI_MAX_UTF8_BYTES_PER_CODE_POINT * Source.size());
  249. UTF8 *ResultPtr = reinterpret_cast<UTF8 *>(&Result[0]);
  250. UTF8 *ResultEnd = reinterpret_cast<UTF8 *>(&Result[0] + Result.size());
  251. if (ConvertUTF32toUTF8(&Start, End, &ResultPtr, ResultEnd,
  252. strictConversion) == conversionOK) {
  253. Result.resize(reinterpret_cast<char *>(ResultPtr) - &Result[0]);
  254. return true;
  255. } else {
  256. Result.clear();
  257. return false;
  258. }
  259. } else {
  260. llvm_unreachable(
  261. "Control should never reach this point; see static_assert further up");
  262. }
  263. }
  264. } // end namespace llvm