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