Rafael Espindola | 454adf6 | 2015-06-13 12:49:52 +0000 | [diff] [blame] | 1 | //===-- StringSaver.cpp ---------------------------------------------------===// |
| 2 | // |
Chandler Carruth | 2946cd7 | 2019-01-19 08:50:56 +0000 | [diff] [blame] | 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 |
Rafael Espindola | 454adf6 | 2015-06-13 12:49:52 +0000 | [diff] [blame] | 6 | // |
| 7 | //===----------------------------------------------------------------------===// |
| 8 | |
| 9 | #include "llvm/Support/StringSaver.h" |
| 10 | |
| 11 | using namespace llvm; |
| 12 | |
Mehdi Amini | ec4fb5b | 2016-10-05 01:32:41 +0000 | [diff] [blame] | 13 | StringRef StringSaver::save(StringRef S) { |
Rafael Espindola | 454adf6 | 2015-06-13 12:49:52 +0000 | [diff] [blame] | 14 | char *P = Alloc.Allocate<char>(S.size() + 1); |
Haojian Wu | 54829bb | 2018-08-20 13:12:54 +0000 | [diff] [blame] | 15 | if (!S.empty()) |
| 16 | memcpy(P, S.data(), S.size()); |
Rafael Espindola | 454adf6 | 2015-06-13 12:49:52 +0000 | [diff] [blame] | 17 | P[S.size()] = '\0'; |
Mehdi Amini | ec4fb5b | 2016-10-05 01:32:41 +0000 | [diff] [blame] | 18 | return StringRef(P, S.size()); |
Rafael Espindola | 454adf6 | 2015-06-13 12:49:52 +0000 | [diff] [blame] | 19 | } |
Sam McCall | 4bb7883d | 2018-07-23 10:44:40 +0000 | [diff] [blame] | 20 | |
| 21 | StringRef UniqueStringSaver::save(StringRef S) { |
Eric Christopher | dad2e92 | 2020-05-14 19:16:45 -0700 | [diff] [blame] | 22 | auto R = Unique.insert(S); |
| 23 | if (R.second) // cache miss, need to actually save the string |
| 24 | *R.first = Strings.save(S); // safe replacement with equal value |
| 25 | return *R.first; |
Sam McCall | 4bb7883d | 2018-07-23 10:44:40 +0000 | [diff] [blame] | 26 | } |