StringSaver.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- llvm/Support/StringSaver.h -------------------------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #ifndef LLVM_SUPPORT_STRINGSAVER_H
  14. #define LLVM_SUPPORT_STRINGSAVER_H
  15. #include "llvm/ADT/DenseSet.h"
  16. #include "llvm/ADT/StringRef.h"
  17. #include "llvm/ADT/Twine.h"
  18. #include "llvm/Support/Allocator.h"
  19. namespace llvm {
  20. /// Saves strings in the provided stable storage and returns a
  21. /// StringRef with a stable character pointer.
  22. class StringSaver final {
  23. BumpPtrAllocator &Alloc;
  24. public:
  25. StringSaver(BumpPtrAllocator &Alloc) : Alloc(Alloc) {}
  26. BumpPtrAllocator &getAllocator() const { return Alloc; }
  27. // All returned strings are null-terminated: *save(S).end() == 0.
  28. StringRef save(const char *S) { return save(StringRef(S)); }
  29. StringRef save(StringRef S);
  30. StringRef save(const Twine &S) { return save(StringRef(S.str())); }
  31. StringRef save(const std::string &S) { return save(StringRef(S)); }
  32. };
  33. /// Saves strings in the provided stable storage and returns a StringRef with a
  34. /// stable character pointer. Saving the same string yields the same StringRef.
  35. ///
  36. /// Compared to StringSaver, it does more work but avoids saving the same string
  37. /// multiple times.
  38. ///
  39. /// Compared to StringPool, it performs fewer allocations but doesn't support
  40. /// refcounting/deletion.
  41. class UniqueStringSaver final {
  42. StringSaver Strings;
  43. llvm::DenseSet<llvm::StringRef> Unique;
  44. public:
  45. UniqueStringSaver(BumpPtrAllocator &Alloc) : Strings(Alloc) {}
  46. // All returned strings are null-terminated: *save(S).end() == 0.
  47. StringRef save(const char *S) { return save(StringRef(S)); }
  48. StringRef save(StringRef S);
  49. StringRef save(const Twine &S) { return save(StringRef(S.str())); }
  50. StringRef save(const std::string &S) { return save(StringRef(S)); }
  51. };
  52. }
  53. #endif
  54. #ifdef __GNUC__
  55. #pragma GCC diagnostic pop
  56. #endif