1 /*
2 * Copyright 2006 The Android Open Source Project
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #ifndef SkString_DEFINED
9 #define SkString_DEFINED
10
11 #include "include/core/SkRefCnt.h"
12 #include "include/core/SkScalar.h"
13 #include "include/core/SkTypes.h"
14 #include "include/private/base/SkTArray.h"
15 #include "include/private/base/SkTo.h"
16 #include "include/private/base/SkTypeTraits.h"
17
18 #include <atomic>
19 #include <cstdarg>
20 #include <cstddef>
21 #include <cstdint>
22 #include <string>
23 #include <string_view>
24 #include <type_traits>
25
26 /* Some helper functions for C strings */
SkStrStartsWith(const char string[],const char prefixStr[])27 static inline bool SkStrStartsWith(const char string[], const char prefixStr[]) {
28 SkASSERT(string);
29 SkASSERT(prefixStr);
30 return !strncmp(string, prefixStr, strlen(prefixStr));
31 }
SkStrStartsWith(const char string[],const char prefixChar)32 static inline bool SkStrStartsWith(const char string[], const char prefixChar) {
33 SkASSERT(string);
34 return (prefixChar == *string);
35 }
36
37 bool SkStrEndsWith(const char string[], const char suffixStr[]);
38 bool SkStrEndsWith(const char string[], const char suffixChar);
39
40 int SkStrStartsWithOneOf(const char string[], const char prefixes[]);
41
SkStrFind(const char string[],const char substring[])42 static inline int SkStrFind(const char string[], const char substring[]) {
43 const char *first = strstr(string, substring);
44 if (nullptr == first) return -1;
45 return SkToInt(first - &string[0]);
46 }
47
SkStrFindLastOf(const char string[],const char subchar)48 static inline int SkStrFindLastOf(const char string[], const char subchar) {
49 const char* last = strrchr(string, subchar);
50 if (nullptr == last) return -1;
51 return SkToInt(last - &string[0]);
52 }
53
SkStrContains(const char string[],const char substring[])54 static inline bool SkStrContains(const char string[], const char substring[]) {
55 SkASSERT(string);
56 SkASSERT(substring);
57 return (-1 != SkStrFind(string, substring));
58 }
SkStrContains(const char string[],const char subchar)59 static inline bool SkStrContains(const char string[], const char subchar) {
60 SkASSERT(string);
61 char tmp[2];
62 tmp[0] = subchar;
63 tmp[1] = '\0';
64 return (-1 != SkStrFind(string, tmp));
65 }
66
67 /*
68 * The SkStrAppend... methods will write into the provided buffer, assuming it is large enough.
69 * Each method has an associated const (e.g. kSkStrAppendU32_MaxSize) which will be the largest
70 * value needed for that method's buffer.
71 *
72 * char storage[kSkStrAppendU32_MaxSize];
73 * SkStrAppendU32(storage, value);
74 *
75 * Note : none of the SkStrAppend... methods write a terminating 0 to their buffers. Instead,
76 * the methods return the ptr to the end of the written part of the buffer. This can be used
77 * to compute the length, and/or know where to write a 0 if that is desired.
78 *
79 * char storage[kSkStrAppendU32_MaxSize + 1];
80 * char* stop = SkStrAppendU32(storage, value);
81 * size_t len = stop - storage;
82 * *stop = 0; // valid, since storage was 1 byte larger than the max.
83 */
84
85 static constexpr int kSkStrAppendU32_MaxSize = 10;
86 char* SkStrAppendU32(char buffer[], uint32_t);
87 static constexpr int kSkStrAppendU64_MaxSize = 20;
88 char* SkStrAppendU64(char buffer[], uint64_t, int minDigits);
89
90 static constexpr int kSkStrAppendS32_MaxSize = kSkStrAppendU32_MaxSize + 1;
91 char* SkStrAppendS32(char buffer[], int32_t);
92 static constexpr int kSkStrAppendS64_MaxSize = kSkStrAppendU64_MaxSize + 1;
93 char* SkStrAppendS64(char buffer[], int64_t, int minDigits);
94
95 /**
96 * Floats have at most 8 significant digits, so we limit our %g to that.
97 * However, the total string could be 15 characters: -1.2345678e-005
98 *
99 * In theory we should only expect up to 2 digits for the exponent, but on
100 * some platforms we have seen 3 (as in the example above).
101 */
102 static constexpr int kSkStrAppendScalar_MaxSize = 15;
103
104 /**
105 * Write the scalar in decimal format into buffer, and return a pointer to
106 * the next char after the last one written. Note: a terminating 0 is not
107 * written into buffer, which must be at least kSkStrAppendScalar_MaxSize.
108 * Thus if the caller wants to add a 0 at the end, buffer must be at least
109 * kSkStrAppendScalar_MaxSize + 1 bytes large.
110 */
111 char* SkStrAppendScalar(char buffer[], SkScalar);
112
113 /** \class SkString
114
115 Light weight class for managing strings. Uses reference
116 counting to make string assignments and copies very fast
117 with no extra RAM cost. Assumes UTF8 encoding.
118 */
119 class SK_API SkString {
120 public:
121 SkString();
122 explicit SkString(size_t len);
123 explicit SkString(const char text[]);
124 SkString(const char text[], size_t len);
125 SkString(const SkString&);
126 SkString(SkString&&);
127 explicit SkString(const std::string&);
128 explicit SkString(std::string_view);
129 ~SkString();
130
isEmpty()131 bool isEmpty() const { return 0 == fRec->fLength; }
size()132 size_t size() const { return (size_t) fRec->fLength; }
data()133 const char* data() const { return fRec->data(); }
c_str()134 const char* c_str() const { return fRec->data(); }
135 char operator[](size_t n) const { return this->c_str()[n]; }
136
137 bool equals(const SkString&) const;
138 bool equals(const char text[]) const;
139 bool equals(const char text[], size_t len) const;
140
startsWith(const char prefixStr[])141 bool startsWith(const char prefixStr[]) const {
142 return SkStrStartsWith(fRec->data(), prefixStr);
143 }
startsWith(const char prefixChar)144 bool startsWith(const char prefixChar) const {
145 return SkStrStartsWith(fRec->data(), prefixChar);
146 }
endsWith(const char suffixStr[])147 bool endsWith(const char suffixStr[]) const {
148 return SkStrEndsWith(fRec->data(), suffixStr);
149 }
endsWith(const char suffixChar)150 bool endsWith(const char suffixChar) const {
151 return SkStrEndsWith(fRec->data(), suffixChar);
152 }
contains(const char substring[])153 bool contains(const char substring[]) const {
154 return SkStrContains(fRec->data(), substring);
155 }
contains(const char subchar)156 bool contains(const char subchar) const {
157 return SkStrContains(fRec->data(), subchar);
158 }
find(const char substring[])159 int find(const char substring[]) const {
160 return SkStrFind(fRec->data(), substring);
161 }
findLastOf(const char subchar)162 int findLastOf(const char subchar) const {
163 return SkStrFindLastOf(fRec->data(), subchar);
164 }
165
166 friend bool operator==(const SkString& a, const SkString& b) {
167 return a.equals(b);
168 }
169 friend bool operator!=(const SkString& a, const SkString& b) {
170 return !a.equals(b);
171 }
172
173 // these methods edit the string
174
175 SkString& operator=(const SkString&);
176 SkString& operator=(SkString&&);
177 SkString& operator=(const char text[]);
178
179 char* data();
180 char& operator[](size_t n) { return this->data()[n]; }
181
182 void reset();
183 /** String contents are preserved on resize. (For destructive resize, `set(nullptr, length)`.)
184 * `resize` automatically reserves an extra byte at the end of the buffer for a null terminator.
185 */
186 void resize(size_t len);
set(const SkString & src)187 void set(const SkString& src) { *this = src; }
188 void set(const char text[]);
189 void set(const char text[], size_t len);
set(std::string_view str)190 void set(std::string_view str) { this->set(str.data(), str.size()); }
191
192 void insert(size_t offset, const char text[]);
193 void insert(size_t offset, const char text[], size_t len);
insert(size_t offset,const SkString & str)194 void insert(size_t offset, const SkString& str) { this->insert(offset, str.c_str(), str.size()); }
insert(size_t offset,std::string_view str)195 void insert(size_t offset, std::string_view str) { this->insert(offset, str.data(), str.size()); }
196 void insertUnichar(size_t offset, SkUnichar);
197 void insertS32(size_t offset, int32_t value);
198 void insertS64(size_t offset, int64_t value, int minDigits = 0);
199 void insertU32(size_t offset, uint32_t value);
200 void insertU64(size_t offset, uint64_t value, int minDigits = 0);
201 void insertHex(size_t offset, uint32_t value, int minDigits = 0);
202 void insertScalar(size_t offset, SkScalar);
203
append(const char text[])204 void append(const char text[]) { this->insert((size_t)-1, text); }
append(const char text[],size_t len)205 void append(const char text[], size_t len) { this->insert((size_t)-1, text, len); }
append(const SkString & str)206 void append(const SkString& str) { this->insert((size_t)-1, str.c_str(), str.size()); }
append(std::string_view str)207 void append(std::string_view str) { this->insert((size_t)-1, str.data(), str.size()); }
appendUnichar(SkUnichar uni)208 void appendUnichar(SkUnichar uni) { this->insertUnichar((size_t)-1, uni); }
appendS32(int32_t value)209 void appendS32(int32_t value) { this->insertS32((size_t)-1, value); }
210 void appendS64(int64_t value, int minDigits = 0) { this->insertS64((size_t)-1, value, minDigits); }
appendU32(uint32_t value)211 void appendU32(uint32_t value) { this->insertU32((size_t)-1, value); }
212 void appendU64(uint64_t value, int minDigits = 0) { this->insertU64((size_t)-1, value, minDigits); }
213 void appendHex(uint32_t value, int minDigits = 0) { this->insertHex((size_t)-1, value, minDigits); }
appendScalar(SkScalar value)214 void appendScalar(SkScalar value) { this->insertScalar((size_t)-1, value); }
215
prepend(const char text[])216 void prepend(const char text[]) { this->insert(0, text); }
prepend(const char text[],size_t len)217 void prepend(const char text[], size_t len) { this->insert(0, text, len); }
prepend(const SkString & str)218 void prepend(const SkString& str) { this->insert(0, str.c_str(), str.size()); }
prepend(std::string_view str)219 void prepend(std::string_view str) { this->insert(0, str.data(), str.size()); }
prependUnichar(SkUnichar uni)220 void prependUnichar(SkUnichar uni) { this->insertUnichar(0, uni); }
prependS32(int32_t value)221 void prependS32(int32_t value) { this->insertS32(0, value); }
222 void prependS64(int32_t value, int minDigits = 0) { this->insertS64(0, value, minDigits); }
223 void prependHex(uint32_t value, int minDigits = 0) { this->insertHex(0, value, minDigits); }
prependScalar(SkScalar value)224 void prependScalar(SkScalar value) { this->insertScalar((size_t)-1, value); }
225
226 void printf(const char format[], ...) SK_PRINTF_LIKE(2, 3);
227 void printVAList(const char format[], va_list) SK_PRINTF_LIKE(2, 0);
228 void appendf(const char format[], ...) SK_PRINTF_LIKE(2, 3);
229 void appendVAList(const char format[], va_list) SK_PRINTF_LIKE(2, 0);
230 void prependf(const char format[], ...) SK_PRINTF_LIKE(2, 3);
231 void prependVAList(const char format[], va_list) SK_PRINTF_LIKE(2, 0);
232
233 void remove(size_t offset, size_t length);
234
235 SkString& operator+=(const SkString& s) { this->append(s); return *this; }
236 SkString& operator+=(const char text[]) { this->append(text); return *this; }
237 SkString& operator+=(const char c) { this->append(&c, 1); return *this; }
238
239 /**
240 * Swap contents between this and other. This function is guaranteed
241 * to never fail or throw.
242 */
243 void swap(SkString& other);
244
245 using sk_is_trivially_relocatable = std::true_type;
246
247 private:
248 struct Rec {
249 public:
RecRec250 constexpr Rec(uint32_t len, int32_t refCnt) : fLength(len), fRefCnt(refCnt) {}
251 static sk_sp<Rec> Make(const char text[], size_t len);
dataRec252 char* data() { return fBeginningOfData; }
dataRec253 const char* data() const { return fBeginningOfData; }
254 void ref() const;
255 void unref() const;
256 bool unique() const;
257 #ifdef SK_DEBUG
258 int32_t getRefCnt() const;
259 #endif
260 uint32_t fLength; // logically size_t, but we want it to stay 32 bits
261
262 private:
263 mutable std::atomic<int32_t> fRefCnt;
264 char fBeginningOfData[1] = {'\0'};
265
266 // Ensure the unsized delete is called.
deleteRec267 void operator delete(void* p) { ::operator delete(p); }
268 };
269 sk_sp<Rec> fRec;
270
271 static_assert(::sk_is_trivially_relocatable<decltype(fRec)>::value);
272
273 #ifdef SK_DEBUG
274 const SkString& validate() const;
275 #else
validate()276 const SkString& validate() const { return *this; }
277 #endif
278
279 static const Rec gEmptyRec;
280 };
281
282 /// Creates a new string and writes into it using a printf()-style format.
283 SkString SkStringPrintf(const char* format, ...) SK_PRINTF_LIKE(1, 2);
284 /// This makes it easier to write a caller as a VAR_ARGS function where the format string is
285 /// optional.
SkStringPrintf()286 static inline SkString SkStringPrintf() { return SkString(); }
287
swap(SkString & a,SkString & b)288 static inline void swap(SkString& a, SkString& b) {
289 a.swap(b);
290 }
291
292 enum SkStrSplitMode {
293 // Strictly return all results. If the input is ",," and the separator is ',' this will return
294 // an array of three empty strings.
295 kStrict_SkStrSplitMode,
296
297 // Only nonempty results will be added to the results. Multiple separators will be
298 // coalesced. Separators at the beginning and end of the input will be ignored. If the input is
299 // ",," and the separator is ',', this will return an empty vector.
300 kCoalesce_SkStrSplitMode
301 };
302
303 // Split str on any characters in delimiters into out. (Think, strtok with a sane API.)
304 void SkStrSplit(const char* str, const char* delimiters, SkStrSplitMode splitMode,
305 SkTArray<SkString>* out);
SkStrSplit(const char * str,const char * delimiters,SkTArray<SkString> * out)306 inline void SkStrSplit(const char* str, const char* delimiters, SkTArray<SkString>* out) {
307 SkStrSplit(str, delimiters, kCoalesce_SkStrSplitMode, out);
308 }
309
310 #endif
311