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