• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- llvm/Support/StringSaver.h -------------------------------*- 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 LLVM_SUPPORT_STRINGSAVER_H
11 #define LLVM_SUPPORT_STRINGSAVER_H
12 
13 #include "llvm/ADT/DenseSet.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/Twine.h"
16 #include "llvm/Support/Allocator.h"
17 
18 namespace llvm {
19 
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 
25 public:
StringSaver(BumpPtrAllocator & Alloc)26   StringSaver(BumpPtrAllocator &Alloc) : Alloc(Alloc) {}
27 
28   // All returned strings are null-terminated: *save(S).end() == 0.
save(const char * S)29   StringRef save(const char *S) { return save(StringRef(S)); }
30   StringRef save(StringRef S);
save(const Twine & S)31   StringRef save(const Twine &S) { return save(StringRef(S.str())); }
save(const std::string & S)32   StringRef save(const std::string &S) { return save(StringRef(S)); }
33 };
34 
35 /// Saves strings in the provided stable storage and returns a StringRef with a
36 /// stable character pointer. Saving the same string yields the same StringRef.
37 ///
38 /// Compared to StringSaver, it does more work but avoids saving the same string
39 /// multiple times.
40 ///
41 /// Compared to StringPool, it performs fewer allocations but doesn't support
42 /// refcounting/deletion.
43 class UniqueStringSaver final {
44   StringSaver Strings;
45   llvm::DenseSet<llvm::StringRef> Unique;
46 
47 public:
UniqueStringSaver(BumpPtrAllocator & Alloc)48   UniqueStringSaver(BumpPtrAllocator &Alloc) : Strings(Alloc) {}
49 
50   // All returned strings are null-terminated: *save(S).end() == 0.
save(const char * S)51   StringRef save(const char *S) { return save(StringRef(S)); }
52   StringRef save(StringRef S);
save(const Twine & S)53   StringRef save(const Twine &S) { return save(StringRef(S.str())); }
save(const std::string & S)54   StringRef save(const std::string &S) { return save(StringRef(S)); }
55 };
56 
57 }
58 #endif
59