StringTableBuilder.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //===-- StringTableBuilder.h - String table building utility ------*- 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. #ifndef LLVM_MC_STRINGTABLEBUILDER_H
  10. #define LLVM_MC_STRINGTABLEBUILDER_H
  11. #include "llvm/ADT/SmallString.h"
  12. #include "llvm/ADT/StringMap.h"
  13. #include <cassert>
  14. namespace llvm {
  15. /// \brief Utility for building string tables with deduplicated suffixes.
  16. class StringTableBuilder {
  17. SmallString<256> StringTable;
  18. StringMap<size_t> StringIndexMap;
  19. public:
  20. /// \brief Add a string to the builder. Returns a StringRef to the internal
  21. /// copy of s. Can only be used before the table is finalized.
  22. StringRef add(StringRef s) {
  23. assert(!isFinalized());
  24. return StringIndexMap.insert(std::make_pair(s, 0)).first->first();
  25. }
  26. enum Kind {
  27. ELF,
  28. WinCOFF,
  29. MachO
  30. };
  31. /// \brief Analyze the strings and build the final table. No more strings can
  32. /// be added after this point.
  33. void finalize(Kind kind);
  34. /// \brief Retrieve the string table data. Can only be used after the table
  35. /// is finalized.
  36. StringRef data() {
  37. assert(isFinalized());
  38. return StringTable;
  39. }
  40. /// \brief Get the offest of a string in the string table. Can only be used
  41. /// after the table is finalized.
  42. size_t getOffset(StringRef s) {
  43. assert(isFinalized());
  44. assert(StringIndexMap.count(s) && "String is not in table!");
  45. return StringIndexMap[s];
  46. }
  47. void clear();
  48. private:
  49. bool isFinalized() {
  50. return !StringTable.empty();
  51. }
  52. };
  53. } // end llvm namespace
  54. #endif