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 operator bool() const { return !!value; }
42
43 const char* value;
44 };
45
46 // A explicit wrapper for marking strings as dynamic to ensure that perfetto
47 // doesn't try to cache the pointer value.
48 class PERFETTO_EXPORT_COMPONENT DynamicString {
49 public:
DynamicString(const std::string & str)50 explicit DynamicString(const std::string& str)
51 : value(str.data()), length(str.length()) {}
DynamicString(const char * str)52 explicit DynamicString(const char* str) : value(str) {
53 PERFETTO_DCHECK(str);
54 length = strlen(str);
55 }
DynamicString(const char * str,size_t len)56 DynamicString(const char* str, size_t len) : value(str), length(len) {}
DynamicString()57 constexpr DynamicString() : value(nullptr), length(0) {}
58
59 operator bool() const { return !!value; }
60
61 const char* value;
62 size_t length;
63 };
64
65 namespace internal {
66
67 template <size_t N>
GetStaticString(const char (& string)[N])68 constexpr const char* GetStaticString(const char (&string)[N]) {
69 return string;
70 }
71
GetStaticString(std::nullptr_t)72 constexpr std::nullptr_t GetStaticString(std::nullptr_t) {
73 return nullptr;
74 }
75
GetStaticString(perfetto::StaticString string)76 constexpr const char* GetStaticString(perfetto::StaticString string) {
77 return string.value;
78 }
79
80 } // namespace internal
81 } // namespace perfetto
82
83 #endif // INCLUDE_PERFETTO_TRACING_STRING_HELPERS_H_
84