blob: 6b77d487333b4a5e68edc64712bffc9f7c1a1fb1 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- 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
Andrew Scullcdfcccc2018-10-05 20:58:37 +010013#include "llvm/ADT/DenseSet.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010014#include "llvm/ADT/StringRef.h"
15#include "llvm/ADT/Twine.h"
16#include "llvm/Support/Allocator.h"
17
18namespace llvm {
19
Andrew Scullcdfcccc2018-10-05 20:58:37 +010020/// Saves strings in the provided stable storage and returns a
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010021/// StringRef with a stable character pointer.
22class StringSaver final {
23 BumpPtrAllocator &Alloc;
24
25public:
26 StringSaver(BumpPtrAllocator &Alloc) : Alloc(Alloc) {}
Andrew Scullcdfcccc2018-10-05 20:58:37 +010027
28 // All returned strings are null-terminated: *save(S).end() == 0.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010029 StringRef save(const char *S) { return save(StringRef(S)); }
30 StringRef save(StringRef S);
31 StringRef save(const Twine &S) { return save(StringRef(S.str())); }
32 StringRef save(const std::string &S) { return save(StringRef(S)); }
33};
Andrew Scullcdfcccc2018-10-05 20:58:37 +010034
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.
43class UniqueStringSaver final {
44 StringSaver Strings;
45 llvm::DenseSet<llvm::StringRef> Unique;
46
47public:
48 UniqueStringSaver(BumpPtrAllocator &Alloc) : Strings(Alloc) {}
49
50 // All returned strings are null-terminated: *save(S).end() == 0.
51 StringRef save(const char *S) { return save(StringRef(S)); }
52 StringRef save(StringRef S);
53 StringRef save(const Twine &S) { return save(StringRef(S.str())); }
54 StringRef save(const std::string &S) { return save(StringRef(S)); }
55};
56
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010057}
58#endif