StringSaver.h 1.9 KB

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