Add CXString.cpp and CXString.h
[clang.git] / tools / libclang / CXString.cpp
blob341b72032dfe264c73b3d99b03e4e40211292a89
1 //===- CXString.cpp - Routines for manipulating CXStrings -----------------===//
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 // This file defines routines for manipulating CXStrings. It should be the
11 // only file that has internal knowledge of the encoding of the data in
12 // CXStrings.
14 //===----------------------------------------------------------------------===//
16 #include "CXString.h"
17 #include "clang/Frontend/ASTUnit.h"
18 #include "clang-c/Index.h"
19 #include "llvm/Support/ErrorHandling.h"
21 using namespace clang;
22 using namespace clang::cxstring;
24 enum CXStringFlag { CXS_Unmanaged, CXS_Malloc };
26 CXString cxstring::createCXString(const char *String, bool DupString){
27 CXString Str;
28 if (DupString) {
29 Str.Spelling = strdup(String);
30 Str.private_flags = (unsigned) CXS_Malloc;
31 } else {
32 Str.Spelling = String;
33 Str.private_flags = (unsigned) CXS_Unmanaged;
35 return Str;
38 CXString cxstring::createCXString(llvm::StringRef String, bool DupString) {
39 CXString Result;
40 if (DupString || (!String.empty() && String.data()[String.size()] != 0)) {
41 char *Spelling = (char *)malloc(String.size() + 1);
42 memmove(Spelling, String.data(), String.size());
43 Spelling[String.size()] = 0;
44 Result.Spelling = Spelling;
45 Result.private_flags = (unsigned) CXS_Malloc;
46 } else {
47 Result.Spelling = String.data();
48 Result.private_flags = (unsigned) CXS_Unmanaged;
50 return Result;
53 //===----------------------------------------------------------------------===//
54 // libClang public APIs.
55 //===----------------------------------------------------------------------===//
57 extern "C" {
58 const char *clang_getCString(CXString string) {
59 return string.Spelling;
62 void clang_disposeString(CXString string) {
63 if (string.private_flags == CXS_Malloc && string.Spelling)
64 free((void*)string.Spelling);
66 } // end: extern "C"