move StringToOffsetTable out to its own header.
[oota-llvm.git] / utils / TableGen / StringToOffsetTable.h
1 //===- StringToOffsetTable.h - Emit a big concatenated string ---*- C++ -*-===//
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 #ifndef TBLGEN_STRING_TO_OFFSET_TABLE_H
11 #define TBLGEN_STRING_TO_OFFSET_TABLE_H
12
13 #include "llvm/ADT/StringMap.h"
14 #include "llvm/Support/raw_ostream.h"
15 #include "llvm/ADT/StringExtras.h"
16
17 namespace llvm {
18
19 /// StringToOffsetTable - This class uniques a bunch of nul-terminated strings
20 /// and keeps track of their offset in a massive contiguous string allocation.
21 /// It can then output this string blob and use indexes into the string to
22 /// reference each piece.
23 class StringToOffsetTable {
24   StringMap<unsigned> StringOffset;
25   std::string AggregateString;
26 public:
27   
28   unsigned GetOrAddStringOffset(StringRef Str) {
29     unsigned &Entry = StringOffset[Str];
30     if (Entry == 0) {
31       // Add the string to the aggregate if this is the first time found.
32       Entry = AggregateString.size();
33       AggregateString.append(Str.begin(), Str.end());
34       AggregateString += '\0';
35     }
36     
37     return Entry;
38   }
39   
40   void EmitString(raw_ostream &O) {
41     O << "    \"";
42     unsigned CharsPrinted = 0;
43     EscapeString(AggregateString);
44     for (unsigned i = 0, e = AggregateString.size(); i != e; ++i) {
45       if (CharsPrinted > 70) {
46         O << "\"\n    \"";
47         CharsPrinted = 0;
48       }
49       O << AggregateString[i];
50       ++CharsPrinted;
51       
52       // Print escape sequences all together.
53       if (AggregateString[i] != '\\')
54         continue;
55       
56       assert(i+1 < AggregateString.size() && "Incomplete escape sequence!");
57       if (isdigit(AggregateString[i+1])) {
58         assert(isdigit(AggregateString[i+2]) && 
59                isdigit(AggregateString[i+3]) &&
60                "Expected 3 digit octal escape!");
61         O << AggregateString[++i];
62         O << AggregateString[++i];
63         O << AggregateString[++i];
64         CharsPrinted += 3;
65       } else {
66         O << AggregateString[++i];
67         ++CharsPrinted;
68       }
69     }
70     O << "\"";
71   }
72 };
73
74 } // end namespace llvm
75
76 #endif