1 | //===-- StringSaver.cpp ---------------------------------------------------===// |
---|---|
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 | #include "llvm/Support/StringSaver.h" |
10 | |
11 | #include "llvm/ADT/SmallString.h" |
12 | |
13 | using namespace llvm; |
14 | |
15 | StringRef StringSaver::save(StringRef S) { |
16 | char *P = Alloc.Allocate<char>(Num: S.size() + 1); |
17 | if (!S.empty()) |
18 | memcpy(dest: P, src: S.data(), n: S.size()); |
19 | P[S.size()] = '\0'; |
20 | return StringRef(P, S.size()); |
21 | } |
22 | |
23 | StringRef StringSaver::save(const Twine &S) { |
24 | SmallString<128> Storage; |
25 | return save(S: S.toStringRef(Out&: Storage)); |
26 | } |
27 | |
28 | StringRef UniqueStringSaver::save(StringRef S) { |
29 | auto R = Unique.insert(V: S); |
30 | if (R.second) // cache miss, need to actually save the string |
31 | *R.first = Strings.save(S); // safe replacement with equal value |
32 | return *R.first; |
33 | } |
34 | |
35 | StringRef UniqueStringSaver::save(const Twine &S) { |
36 | SmallString<128> Storage; |
37 | return save(S: S.toStringRef(Out&: Storage)); |
38 | } |
39 |