13a0822f0SDimitry Andric //===-- StringSaver.cpp ---------------------------------------------------===// 23a0822f0SDimitry Andric // 3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 63a0822f0SDimitry Andric // 73a0822f0SDimitry Andric //===----------------------------------------------------------------------===// 83a0822f0SDimitry Andric 93a0822f0SDimitry Andric #include "llvm/Support/StringSaver.h" 103a0822f0SDimitry Andric 11b1c73532SDimitry Andric #include "llvm/ADT/SmallString.h" 12b1c73532SDimitry Andric 133a0822f0SDimitry Andric using namespace llvm; 143a0822f0SDimitry Andric save(StringRef S)15b915e9e0SDimitry AndricStringRef StringSaver::save(StringRef S) { 163a0822f0SDimitry Andric char *P = Alloc.Allocate<char>(S.size() + 1); 17d8e91e46SDimitry Andric if (!S.empty()) 183a0822f0SDimitry Andric memcpy(P, S.data(), S.size()); 193a0822f0SDimitry Andric P[S.size()] = '\0'; 20b915e9e0SDimitry Andric return StringRef(P, S.size()); 213a0822f0SDimitry Andric } 22eb11fae6SDimitry Andric save(const Twine & S)23b1c73532SDimitry AndricStringRef StringSaver::save(const Twine &S) { 24b1c73532SDimitry Andric SmallString<128> Storage; 25b1c73532SDimitry Andric return save(S.toStringRef(Storage)); 26b1c73532SDimitry Andric } 27b1c73532SDimitry Andric save(StringRef S)28eb11fae6SDimitry AndricStringRef UniqueStringSaver::save(StringRef S) { 29eb11fae6SDimitry Andric auto R = Unique.insert(S); 30eb11fae6SDimitry Andric if (R.second) // cache miss, need to actually save the string 31eb11fae6SDimitry Andric *R.first = Strings.save(S); // safe replacement with equal value 32eb11fae6SDimitry Andric return *R.first; 33eb11fae6SDimitry Andric } 34b1c73532SDimitry Andric save(const Twine & S)35b1c73532SDimitry AndricStringRef UniqueStringSaver::save(const Twine &S) { 36b1c73532SDimitry Andric SmallString<128> Storage; 37b1c73532SDimitry Andric return save(S.toStringRef(Storage)); 38b1c73532SDimitry Andric } 39