StringSaver.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. // All returned strings are null-terminated: *save(S).end() == 0.
  27. StringRef save(const char *S) { return save(StringRef(S)); }
  28. StringRef save(StringRef S);
  29. StringRef save(const Twine &S) { return save(StringRef(S.str())); }
  30. StringRef save(const std::string &S) { return save(StringRef(S)); }
  31. };
  32. /// Saves strings in the provided stable storage and returns a StringRef with a
  33. /// stable character pointer. Saving the same string yields the same StringRef.
  34. ///
  35. /// Compared to StringSaver, it does more work but avoids saving the same string
  36. /// multiple times.
  37. ///
  38. /// Compared to StringPool, it performs fewer allocations but doesn't support
  39. /// refcounting/deletion.
  40. class UniqueStringSaver final {
  41. StringSaver Strings;
  42. llvm::DenseSet<llvm::StringRef> Unique;
  43. public:
  44. UniqueStringSaver(BumpPtrAllocator &Alloc) : Strings(Alloc) {}
  45. // All returned strings are null-terminated: *save(S).end() == 0.
  46. StringRef save(const char *S) { return save(StringRef(S)); }
  47. StringRef save(StringRef S);
  48. StringRef save(const Twine &S) { return save(StringRef(S.str())); }
  49. StringRef save(const std::string &S) { return save(StringRef(S)); }
  50. };
  51. }
  52. #endif
  53. #ifdef __GNUC__
  54. #pragma GCC diagnostic pop
  55. #endif