1 /* 2 * Copyright (C) 2021 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #ifndef INCLUDE_PERFETTO_TRACING_STRING_HELPERS_H_ 18 #define INCLUDE_PERFETTO_TRACING_STRING_HELPERS_H_ 19 20 #include "perfetto/base/export.h" 21 #include "perfetto/base/logging.h" 22 23 #include <cstddef> 24 #include <string> 25 26 namespace perfetto { 27 28 // A wrapper for marking strings that can't be determined to be static at build 29 // time, but are in fact static. 30 class PERFETTO_EXPORT_COMPONENT StaticString { 31 public: 32 // Implicit constructor for string literals. 33 template <size_t N> StaticString(const char (& str)[N])34 constexpr StaticString(const char (&str)[N]) : value(str) {} 35 36 // Implicit constructor for null strings. StaticString(std::nullptr_t)37 constexpr StaticString(std::nullptr_t) : value(nullptr) {} 38 StaticString(const char * str)39 constexpr explicit StaticString(const char* str) : value(str) {} 40 41 const char* value; 42 }; 43 44 // A explicit wrapper for marking strings as dynamic to ensure that perfetto 45 // doesn't try to cache the pointer value. 46 class PERFETTO_EXPORT_COMPONENT DynamicString { 47 public: DynamicString(const std::string & str)48 explicit DynamicString(const std::string& str) 49 : value(str.data()), length(str.length()) {} DynamicString(const char * str)50 explicit DynamicString(const char* str) : value(str) { 51 PERFETTO_DCHECK(str); 52 length = strlen(str); 53 } DynamicString(const char * str,size_t len)54 DynamicString(const char* str, size_t len) : value(str), length(len) {} 55 56 const char* value; 57 size_t length; 58 }; 59 60 namespace internal { 61 62 template <size_t N> GetStaticString(const char (& string)[N])63constexpr const char* GetStaticString(const char (&string)[N]) { 64 return string; 65 } 66 GetStaticString(std::nullptr_t)67constexpr std::nullptr_t GetStaticString(std::nullptr_t) { 68 return nullptr; 69 } 70 GetStaticString(perfetto::StaticString string)71constexpr const char* GetStaticString(perfetto::StaticString string) { 72 return string.value; 73 } 74 75 } // namespace internal 76 } // namespace perfetto 77 78 #endif // INCLUDE_PERFETTO_TRACING_STRING_HELPERS_H_ 79