LLVM  10.0.0svn
ConvertUTFWrapper.cpp
Go to the documentation of this file.
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 
9 #include "llvm/ADT/ArrayRef.h"
10 #include "llvm/ADT/StringRef.h"
14 #include <string>
15 #include <vector>
16 
17 namespace llvm {
18 
19 bool ConvertUTF8toWide(unsigned WideCharWidth, llvm::StringRef Source,
20  char *&ResultPtr, const UTF8 *&ErrorPtr) {
21  assert(WideCharWidth == 1 || WideCharWidth == 2 || WideCharWidth == 4);
23  // Copy the character span over.
24  if (WideCharWidth == 1) {
25  const UTF8 *Pos = reinterpret_cast<const UTF8*>(Source.begin());
26  if (!isLegalUTF8String(&Pos, reinterpret_cast<const UTF8*>(Source.end()))) {
27  result = sourceIllegal;
28  ErrorPtr = Pos;
29  } else {
30  memcpy(ResultPtr, Source.data(), Source.size());
31  ResultPtr += Source.size();
32  }
33  } else if (WideCharWidth == 2) {
34  const UTF8 *sourceStart = (const UTF8*)Source.data();
35  // FIXME: Make the type of the result buffer correct instead of
36  // using reinterpret_cast.
37  UTF16 *targetStart = reinterpret_cast<UTF16*>(ResultPtr);
39  result = ConvertUTF8toUTF16(
40  &sourceStart, sourceStart + Source.size(),
41  &targetStart, targetStart + Source.size(), flags);
42  if (result == conversionOK)
43  ResultPtr = reinterpret_cast<char*>(targetStart);
44  else
45  ErrorPtr = sourceStart;
46  } else if (WideCharWidth == 4) {
47  const UTF8 *sourceStart = (const UTF8*)Source.data();
48  // FIXME: Make the type of the result buffer correct instead of
49  // using reinterpret_cast.
50  UTF32 *targetStart = reinterpret_cast<UTF32*>(ResultPtr);
52  result = ConvertUTF8toUTF32(
53  &sourceStart, sourceStart + Source.size(),
54  &targetStart, targetStart + Source.size(), flags);
55  if (result == conversionOK)
56  ResultPtr = reinterpret_cast<char*>(targetStart);
57  else
58  ErrorPtr = sourceStart;
59  }
60  assert((result != targetExhausted)
61  && "ConvertUTF8toUTFXX exhausted target buffer");
62  return result == conversionOK;
63 }
64 
65 bool ConvertCodePointToUTF8(unsigned Source, char *&ResultPtr) {
66  const UTF32 *SourceStart = &Source;
67  const UTF32 *SourceEnd = SourceStart + 1;
68  UTF8 *TargetStart = reinterpret_cast<UTF8 *>(ResultPtr);
69  UTF8 *TargetEnd = TargetStart + 4;
70  ConversionResult CR = ConvertUTF32toUTF8(&SourceStart, SourceEnd,
71  &TargetStart, TargetEnd,
73  if (CR != conversionOK)
74  return false;
75 
76  ResultPtr = reinterpret_cast<char*>(TargetStart);
77  return true;
78 }
79 
81  return (S.size() >= 2 &&
82  ((S[0] == '\xff' && S[1] == '\xfe') ||
83  (S[0] == '\xfe' && S[1] == '\xff')));
84 }
85 
86 bool convertUTF16ToUTF8String(ArrayRef<char> SrcBytes, std::string &Out) {
87  assert(Out.empty());
88 
89  // Error out on an uneven byte count.
90  if (SrcBytes.size() % 2)
91  return false;
92 
93  // Avoid OOB by returning early on empty input.
94  if (SrcBytes.empty())
95  return true;
96 
97  const UTF16 *Src = reinterpret_cast<const UTF16 *>(SrcBytes.begin());
98  const UTF16 *SrcEnd = reinterpret_cast<const UTF16 *>(SrcBytes.end());
99 
100  // Byteswap if necessary.
101  std::vector<UTF16> ByteSwapped;
102  if (Src[0] == UNI_UTF16_BYTE_ORDER_MARK_SWAPPED) {
103  ByteSwapped.insert(ByteSwapped.end(), Src, SrcEnd);
104  for (unsigned I = 0, E = ByteSwapped.size(); I != E; ++I)
105  ByteSwapped[I] = llvm::sys::SwapByteOrder_16(ByteSwapped[I]);
106  Src = &ByteSwapped[0];
107  SrcEnd = &ByteSwapped[ByteSwapped.size() - 1] + 1;
108  }
109 
110  // Skip the BOM for conversion.
111  if (Src[0] == UNI_UTF16_BYTE_ORDER_MARK_NATIVE)
112  Src++;
113 
114  // Just allocate enough space up front. We'll shrink it later. Allocate
115  // enough that we can fit a null terminator without reallocating.
116  Out.resize(SrcBytes.size() * UNI_MAX_UTF8_BYTES_PER_CODE_POINT + 1);
117  UTF8 *Dst = reinterpret_cast<UTF8 *>(&Out[0]);
118  UTF8 *DstEnd = Dst + Out.size();
119 
120  ConversionResult CR =
121  ConvertUTF16toUTF8(&Src, SrcEnd, &Dst, DstEnd, strictConversion);
122  assert(CR != targetExhausted);
123 
124  if (CR != conversionOK) {
125  Out.clear();
126  return false;
127  }
128 
129  Out.resize(reinterpret_cast<char *>(Dst) - &Out[0]);
130  Out.push_back(0);
131  Out.pop_back();
132  return true;
133 }
134 
135 bool convertUTF16ToUTF8String(ArrayRef<UTF16> Src, std::string &Out)
136 {
138  llvm::ArrayRef<char>(reinterpret_cast<const char *>(Src.data()),
139  Src.size() * sizeof(UTF16)), Out);
140 }
141 
143  SmallVectorImpl<UTF16> &DstUTF16) {
144  assert(DstUTF16.empty());
145 
146  // Avoid OOB by returning early on empty input.
147  if (SrcUTF8.empty()) {
148  DstUTF16.push_back(0);
149  DstUTF16.pop_back();
150  return true;
151  }
152 
153  const UTF8 *Src = reinterpret_cast<const UTF8 *>(SrcUTF8.begin());
154  const UTF8 *SrcEnd = reinterpret_cast<const UTF8 *>(SrcUTF8.end());
155 
156  // Allocate the same number of UTF-16 code units as UTF-8 code units. Encoding
157  // as UTF-16 should always require the same amount or less code units than the
158  // UTF-8 encoding. Allocate one extra byte for the null terminator though,
159  // so that someone calling DstUTF16.data() gets a null terminated string.
160  // We resize down later so we don't have to worry that this over allocates.
161  DstUTF16.resize(SrcUTF8.size()+1);
162  UTF16 *Dst = &DstUTF16[0];
163  UTF16 *DstEnd = Dst + DstUTF16.size();
164 
165  ConversionResult CR =
166  ConvertUTF8toUTF16(&Src, SrcEnd, &Dst, DstEnd, strictConversion);
167  assert(CR != targetExhausted);
168 
169  if (CR != conversionOK) {
170  DstUTF16.clear();
171  return false;
172  }
173 
174  DstUTF16.resize(Dst - &DstUTF16[0]);
175  DstUTF16.push_back(0);
176  DstUTF16.pop_back();
177  return true;
178 }
179 
180 static_assert(sizeof(wchar_t) == 1 || sizeof(wchar_t) == 2 ||
181  sizeof(wchar_t) == 4,
182  "Expected wchar_t to be 1, 2, or 4 bytes");
183 
184 template <typename TResult>
186  TResult &Result) {
187  // Even in the case of UTF-16, the number of bytes in a UTF-8 string is
188  // at least as large as the number of elements in the resulting wide
189  // string, because surrogate pairs take at least 4 bytes in UTF-8.
190  Result.resize(Source.size() + 1);
191  char *ResultPtr = reinterpret_cast<char *>(&Result[0]);
192  const UTF8 *ErrorPtr;
193  if (!ConvertUTF8toWide(sizeof(wchar_t), Source, ResultPtr, ErrorPtr)) {
194  Result.clear();
195  return false;
196  }
197  Result.resize(reinterpret_cast<wchar_t *>(ResultPtr) - &Result[0]);
198  return true;
199 }
200 
201 bool ConvertUTF8toWide(llvm::StringRef Source, std::wstring &Result) {
202  return ConvertUTF8toWideInternal(Source, Result);
203 }
204 
205 bool ConvertUTF8toWide(const char *Source, std::wstring &Result) {
206  if (!Source) {
207  Result.clear();
208  return true;
209  }
210  return ConvertUTF8toWide(llvm::StringRef(Source), Result);
211 }
212 
213 bool convertWideToUTF8(const std::wstring &Source, std::string &Result) {
214  if (sizeof(wchar_t) == 1) {
215  const UTF8 *Start = reinterpret_cast<const UTF8 *>(Source.data());
216  const UTF8 *End =
217  reinterpret_cast<const UTF8 *>(Source.data() + Source.size());
218  if (!isLegalUTF8String(&Start, End))
219  return false;
220  Result.resize(Source.size());
221  memcpy(&Result[0], Source.data(), Source.size());
222  return true;
223  } else if (sizeof(wchar_t) == 2) {
225  llvm::ArrayRef<UTF16>(reinterpret_cast<const UTF16 *>(Source.data()),
226  Source.size()),
227  Result);
228  } else if (sizeof(wchar_t) == 4) {
229  const UTF32 *Start = reinterpret_cast<const UTF32 *>(Source.data());
230  const UTF32 *End =
231  reinterpret_cast<const UTF32 *>(Source.data() + Source.size());
232  Result.resize(UNI_MAX_UTF8_BYTES_PER_CODE_POINT * Source.size());
233  UTF8 *ResultPtr = reinterpret_cast<UTF8 *>(&Result[0]);
234  UTF8 *ResultEnd = reinterpret_cast<UTF8 *>(&Result[0] + Result.size());
235  if (ConvertUTF32toUTF8(&Start, End, &ResultPtr, ResultEnd,
237  Result.resize(reinterpret_cast<char *>(ResultPtr) - &Result[0]);
238  return true;
239  } else {
240  Result.clear();
241  return false;
242  }
243  } else {
245  "Control should never reach this point; see static_assert further up");
246  }
247 }
248 
249 } // end namespace llvm
250 
unsigned int UTF32
Definition: ConvertUTF.h:109
bool hasUTF16ByteOrderMark(ArrayRef< char > SrcBytes)
Returns true if a blob of text starts with a UTF-16 big or little endian byte order mark...
This class represents lattice values for constants.
Definition: AllocatorList.h:23
iterator begin() const
Definition: ArrayRef.h:136
#define UNI_MAX_UTF8_BYTES_PER_CODE_POINT
Definition: ConvertUTF.h:121
ConversionResult
Definition: ConvertUTF.h:126
unsigned short UTF16
Definition: ConvertUTF.h:110
ConversionResult ConvertUTF8toUTF32(const UTF8 **sourceStart, const UTF8 *sourceEnd, UTF32 **targetStart, UTF32 *targetEnd, ConversionFlags flags)
Convert a partial UTF8 sequence to UTF32.
Definition: ConvertUTF.cpp:710
ConversionResult ConvertUTF16toUTF8(const UTF16 **sourceStart, const UTF16 *sourceEnd, UTF8 **targetStart, UTF8 *targetEnd, ConversionFlags flags)
Definition: ConvertUTF.cpp:247
static bool ConvertUTF8toWideInternal(llvm::StringRef Source, TResult &Result)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:41
#define UNI_UTF16_BYTE_ORDER_MARK_SWAPPED
Definition: ConvertUTF.h:124
unsigned char UTF8
Definition: ConvertUTF.h:111
LLVM_NODISCARD bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:140
#define UNI_UTF16_BYTE_ORDER_MARK_NATIVE
Definition: ConvertUTF.h:123
bool convertWideToUTF8(const std::wstring &Source, std::string &Result)
Converts a std::wstring to a UTF-8 encoded std::string.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:144
bool convertUTF8ToUTF16String(StringRef SrcUTF8, SmallVectorImpl< UTF16 > &DstUTF16)
Converts a UTF-8 string into a UTF-16 string with native endianness.
ConversionResult ConvertUTF8toUTF16(const UTF8 **sourceStart, const UTF8 *sourceEnd, UTF16 **targetStart, UTF16 *targetEnd, ConversionFlags flags)
Definition: ConvertUTF.cpp:541
uint16_t SwapByteOrder_16(uint16_t value)
SwapByteOrder_16 - This function returns a byte-swapped representation of the 16-bit argument...
Definition: SwapByteOrder.h:58
ConversionResult ConvertUTF32toUTF8(const UTF32 **sourceStart, const UTF32 *sourceEnd, UTF8 **targetStart, UTF8 *targetEnd, ConversionFlags flags)
Definition: ConvertUTF.cpp:317
bool ConvertUTF8toWide(unsigned WideCharWidth, llvm::StringRef Source, char *&ResultPtr, const UTF8 *&ErrorPtr)
Convert an UTF8 StringRef to UTF8, UTF16, or UTF32 depending on WideCharWidth.
bool ConvertCodePointToUTF8(unsigned Source, char *&ResultPtr)
Convert an Unicode code point to UTF8 sequence.
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:148
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Boolean isLegalUTF8String(const UTF8 **source, const UTF8 *sourceEnd)
Definition: ConvertUTF.cpp:529
size_t size() const
Definition: SmallVector.h:52
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const T * data() const
Definition: ArrayRef.h:145
ConversionFlags
Definition: ConvertUTF.h:133
iterator end() const
Definition: ArrayRef.h:137
iterator begin() const
Definition: StringRef.h:115
bool convertUTF16ToUTF8String(ArrayRef< char > SrcBytes, std::string &Out)
Converts a stream of raw bytes assumed to be UTF16 into a UTF8 std::string.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_NODISCARD const char * data() const
data - Get a pointer to the start of the string (which may not be null terminated).
Definition: StringRef.h:136
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
iterator end() const
Definition: StringRef.h:117
bool empty() const
empty - Check if the array is empty.
Definition: ArrayRef.h:143
void resize(size_type N)
Definition: SmallVector.h:344