blob: c54044e3986ca64579d7663beb81e315bd72d864 [file] [log] [blame]
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01001//===- llvm/Support/StringSaver.h -------------------------------*- C++ -*-===//
2//
Andrew Walbran16937d02019-10-22 13:54:20 +01003// 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
Andrew Scull5e1ddfa2018-08-14 10:06:54 +01006//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLVM_SUPPORT_STRINGSAVER_H
10#define LLVM_SUPPORT_STRINGSAVER_H
11
Andrew Scullcdfcccc2018-10-05 20:58:37 +010012#include "llvm/ADT/DenseSet.h"
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010013#include "llvm/ADT/StringRef.h"
14#include "llvm/ADT/Twine.h"
15#include "llvm/Support/Allocator.h"
16
17namespace llvm {
18
Andrew Scullcdfcccc2018-10-05 20:58:37 +010019/// Saves strings in the provided stable storage and returns a
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010020/// StringRef with a stable character pointer.
21class StringSaver final {
22 BumpPtrAllocator &Alloc;
23
24public:
25 StringSaver(BumpPtrAllocator &Alloc) : Alloc(Alloc) {}
Andrew Scullcdfcccc2018-10-05 20:58:37 +010026
27 // All returned strings are null-terminated: *save(S).end() == 0.
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010028 StringRef save(const char *S) { return save(StringRef(S)); }
29 StringRef save(StringRef S);
30 StringRef save(const Twine &S) { return save(StringRef(S.str())); }
31 StringRef save(const std::string &S) { return save(StringRef(S)); }
32};
Andrew Scullcdfcccc2018-10-05 20:58:37 +010033
34/// Saves strings in the provided stable storage and returns a StringRef with a
35/// stable character pointer. Saving the same string yields the same StringRef.
36///
37/// Compared to StringSaver, it does more work but avoids saving the same string
38/// multiple times.
39///
40/// Compared to StringPool, it performs fewer allocations but doesn't support
41/// refcounting/deletion.
42class UniqueStringSaver final {
43 StringSaver Strings;
44 llvm::DenseSet<llvm::StringRef> Unique;
45
46public:
47 UniqueStringSaver(BumpPtrAllocator &Alloc) : Strings(Alloc) {}
48
49 // All returned strings are null-terminated: *save(S).end() == 0.
50 StringRef save(const char *S) { return save(StringRef(S)); }
51 StringRef save(StringRef S);
52 StringRef save(const Twine &S) { return save(StringRef(S.str())); }
53 StringRef save(const std::string &S) { return save(StringRef(S)); }
54};
55
Andrew Scull5e1ddfa2018-08-14 10:06:54 +010056}
57#endif