1 //===-- ConvertUTFWrapper.cpp - Wrap ConvertUTF.h with clang data types -----===
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "clang/Basic/ConvertUTF.h"
11 #include "clang/Basic/LLVM.h"
12
13 namespace clang {
14
ConvertUTF8toWide(unsigned WideCharWidth,llvm::StringRef Source,char * & ResultPtr,const UTF8 * & ErrorPtr)15 bool ConvertUTF8toWide(unsigned WideCharWidth, llvm::StringRef Source,
16 char *&ResultPtr, const UTF8 *&ErrorPtr) {
17 assert(WideCharWidth == 1 || WideCharWidth == 2 || WideCharWidth == 4);
18 ConversionResult result = conversionOK;
19 // Copy the character span over.
20 if (WideCharWidth == 1) {
21 const UTF8 *Pos = reinterpret_cast<const UTF8*>(Source.begin());
22 if (!isLegalUTF8String(&Pos, reinterpret_cast<const UTF8*>(Source.end()))) {
23 result = sourceIllegal;
24 ErrorPtr = Pos;
25 } else {
26 memcpy(ResultPtr, Source.data(), Source.size());
27 ResultPtr += Source.size();
28 }
29 } else if (WideCharWidth == 2) {
30 const UTF8 *sourceStart = (const UTF8*)Source.data();
31 // FIXME: Make the type of the result buffer correct instead of
32 // using reinterpret_cast.
33 UTF16 *targetStart = reinterpret_cast<UTF16*>(ResultPtr);
34 ConversionFlags flags = strictConversion;
35 result = ConvertUTF8toUTF16(
36 &sourceStart, sourceStart + Source.size(),
37 &targetStart, targetStart + 2*Source.size(), flags);
38 if (result == conversionOK)
39 ResultPtr = reinterpret_cast<char*>(targetStart);
40 else
41 ErrorPtr = sourceStart;
42 } else if (WideCharWidth == 4) {
43 const UTF8 *sourceStart = (const UTF8*)Source.data();
44 // FIXME: Make the type of the result buffer correct instead of
45 // using reinterpret_cast.
46 UTF32 *targetStart = reinterpret_cast<UTF32*>(ResultPtr);
47 ConversionFlags flags = strictConversion;
48 result = ConvertUTF8toUTF32(
49 &sourceStart, sourceStart + Source.size(),
50 &targetStart, targetStart + 4*Source.size(), flags);
51 if (result == conversionOK)
52 ResultPtr = reinterpret_cast<char*>(targetStart);
53 else
54 ErrorPtr = sourceStart;
55 }
56 assert((result != targetExhausted)
57 && "ConvertUTF8toUTFXX exhausted target buffer");
58 return result == conversionOK;
59 }
60
ConvertCodePointToUTF8(unsigned Source,char * & ResultPtr)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
72 ResultPtr = reinterpret_cast<char*>(TargetStart);
73 return true;
74 }
75
76 } // end namespace clang
77