10b57cec5SDimitry Andric //===-- StringSaver.cpp ---------------------------------------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric 90b57cec5SDimitry Andric #include "llvm/Support/StringSaver.h" 100b57cec5SDimitry Andric 11*5f757f3fSDimitry Andric #include "llvm/ADT/SmallString.h" 12*5f757f3fSDimitry Andric 130b57cec5SDimitry Andric using namespace llvm; 140b57cec5SDimitry Andric 150b57cec5SDimitry Andric StringRef StringSaver::save(StringRef S) { 160b57cec5SDimitry Andric char *P = Alloc.Allocate<char>(S.size() + 1); 170b57cec5SDimitry Andric if (!S.empty()) 180b57cec5SDimitry Andric memcpy(P, S.data(), S.size()); 190b57cec5SDimitry Andric P[S.size()] = '\0'; 200b57cec5SDimitry Andric return StringRef(P, S.size()); 210b57cec5SDimitry Andric } 220b57cec5SDimitry Andric 23*5f757f3fSDimitry Andric StringRef StringSaver::save(const Twine &S) { 24*5f757f3fSDimitry Andric SmallString<128> Storage; 25*5f757f3fSDimitry Andric return save(S.toStringRef(Storage)); 26*5f757f3fSDimitry Andric } 27*5f757f3fSDimitry Andric 280b57cec5SDimitry Andric StringRef UniqueStringSaver::save(StringRef S) { 290b57cec5SDimitry Andric auto R = Unique.insert(S); 300b57cec5SDimitry Andric if (R.second) // cache miss, need to actually save the string 310b57cec5SDimitry Andric *R.first = Strings.save(S); // safe replacement with equal value 320b57cec5SDimitry Andric return *R.first; 330b57cec5SDimitry Andric } 34*5f757f3fSDimitry Andric 35*5f757f3fSDimitry Andric StringRef UniqueStringSaver::save(const Twine &S) { 36*5f757f3fSDimitry Andric SmallString<128> Storage; 37*5f757f3fSDimitry Andric return save(S.toStringRef(Storage)); 38*5f757f3fSDimitry Andric } 39