1 /* 2 * Copyright (c) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 #ifndef STRING_VIEW_UTIL_H 16 #define STRING_VIEW_UTIL_H 17 18 #include <cstdio> 19 #include <string> 20 #include <securec.h> 21 #include <vector> 22 #include <pthread.h> 23 #include "cpp_define.h" 24 25 namespace OHOS { 26 namespace HiviewDFX { 27 class StringViewHold { 28 public: Get()29 static StringViewHold &Get() 30 { 31 static StringViewHold instance; 32 return instance; 33 } 34 Hold(STRING_VIEW view)35 const char* Hold(STRING_VIEW view) 36 { 37 pthread_spin_lock(&spin_lock_); 38 if (view.size() == 0) { 39 pthread_spin_unlock(&spin_lock_); 40 return ""; 41 } 42 43 char *p = new (std::nothrow) char[view.size() + 1]; 44 if (p == nullptr) { 45 pthread_spin_unlock(&spin_lock_); 46 return ""; 47 } 48 if (memset_s(p, view.size() + 1, '\0', view.size() + 1) != 0) { 49 pthread_spin_unlock(&spin_lock_); 50 return ""; 51 } 52 std::copy(view.data(), view.data() + view.size(), p); 53 views_.emplace_back(p); 54 pthread_spin_unlock(&spin_lock_); 55 return p; 56 } 57 58 // only use in UT Clean()59 void Clean() 60 { 61 pthread_spin_lock(&spin_lock_); 62 for (auto &p : views_) { 63 delete[] p; 64 } 65 views_.clear(); 66 pthread_spin_unlock(&spin_lock_); 67 } 68 private: StringViewHold()69 StringViewHold() 70 { 71 pthread_spin_init(&spin_lock_, PTHREAD_PROCESS_PRIVATE); 72 } ~StringViewHold()73 ~StringViewHold() 74 { 75 Clean(); 76 pthread_spin_destroy(&spin_lock_); 77 } 78 79 std::vector<char *> views_; 80 pthread_spinlock_t spin_lock_; 81 }; 82 } // namespace HiviewDFX 83 } // namespace OHOS 84 #endif