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
9 #include "SkAtomics.h"
10 #include "SkString.h"
11 #include "SkUtils.h"
12 #include <stdarg.h>
13 #include <stdio.h>
14
15 // number of bytes (on the stack) to receive the printf result
16 static const size_t kBufferSize = 1024;
17
18 #ifdef SK_BUILD_FOR_WIN
19 #define VSNPRINTF(buffer, size, format, args) \
20 _vsnprintf_s(buffer, size, _TRUNCATE, format, args)
21 #define SNPRINTF _snprintf
22 #else
23 #define VSNPRINTF vsnprintf
24 #define SNPRINTF snprintf
25 #endif
26
27 #define ARGS_TO_BUFFER(format, buffer, size, written) \
28 do { \
29 va_list args; \
30 va_start(args, format); \
31 written = VSNPRINTF(buffer, size, format, args); \
32 SkASSERT(written >= 0 && written < SkToInt(size)); \
33 va_end(args); \
34 } while (0)
35
36 #ifdef SK_BUILD_FOR_WIN
37 #define V_SKSTRING_PRINTF(output, format) \
38 do { \
39 va_list args; \
40 va_start(args, format); \
41 char buffer[kBufferSize]; \
42 int length = _vsnprintf_s(buffer, sizeof(buffer), \
43 _TRUNCATE, format, args); \
44 va_end(args); \
45 if (length >= 0 && length < (int)sizeof(buffer)) { \
46 output.set(buffer, length); \
47 break; \
48 } \
49 va_start(args, format); \
50 length = _vscprintf(format, args); \
51 va_end(args); \
52 SkAutoTMalloc<char> autoTMalloc((size_t)length + 1); \
53 va_start(args, format); \
54 SkDEBUGCODE(int check = ) _vsnprintf_s(autoTMalloc.get(), \
55 length + 1, _TRUNCATE, \
56 format, args); \
57 va_end(args); \
58 SkASSERT(check == length); \
59 output.set(autoTMalloc.get(), length); \
60 SkASSERT(output[length] == '\0'); \
61 } while (false)
62 #else
63 #define V_SKSTRING_PRINTF(output, format) \
64 do { \
65 va_list args; \
66 va_start(args, format); \
67 char buffer[kBufferSize]; \
68 int length = vsnprintf(buffer, sizeof(buffer), format, args); \
69 va_end(args); \
70 if (length < 0) { \
71 break; \
72 } \
73 if (length < (int)sizeof(buffer)) { \
74 output.set(buffer, length); \
75 break; \
76 } \
77 SkAutoTMalloc<char> autoTMalloc((size_t)length + 1); \
78 va_start(args, format); \
79 SkDEBUGCODE(int check = ) vsnprintf(autoTMalloc.get(), \
80 length + 1, format, args); \
81 va_end(args); \
82 SkASSERT(check == length); \
83 output.set(autoTMalloc.get(), length); \
84 SkASSERT(output[length] == '\0'); \
85 } while (false)
86 #endif
87
88 ///////////////////////////////////////////////////////////////////////////////
89
SkStrEndsWith(const char string[],const char suffixStr[])90 bool SkStrEndsWith(const char string[], const char suffixStr[]) {
91 SkASSERT(string);
92 SkASSERT(suffixStr);
93 size_t strLen = strlen(string);
94 size_t suffixLen = strlen(suffixStr);
95 return strLen >= suffixLen &&
96 !strncmp(string + strLen - suffixLen, suffixStr, suffixLen);
97 }
98
SkStrEndsWith(const char string[],const char suffixChar)99 bool SkStrEndsWith(const char string[], const char suffixChar) {
100 SkASSERT(string);
101 size_t strLen = strlen(string);
102 if (0 == strLen) {
103 return false;
104 } else {
105 return (suffixChar == string[strLen-1]);
106 }
107 }
108
SkStrStartsWithOneOf(const char string[],const char prefixes[])109 int SkStrStartsWithOneOf(const char string[], const char prefixes[]) {
110 int index = 0;
111 do {
112 const char* limit = strchr(prefixes, '\0');
113 if (!strncmp(string, prefixes, limit - prefixes)) {
114 return index;
115 }
116 prefixes = limit + 1;
117 index++;
118 } while (prefixes[0]);
119 return -1;
120 }
121
SkStrAppendU32(char string[],uint32_t dec)122 char* SkStrAppendU32(char string[], uint32_t dec) {
123 SkDEBUGCODE(char* start = string;)
124
125 char buffer[SkStrAppendU32_MaxSize];
126 char* p = buffer + sizeof(buffer);
127
128 do {
129 *--p = SkToU8('0' + dec % 10);
130 dec /= 10;
131 } while (dec != 0);
132
133 SkASSERT(p >= buffer);
134 char* stop = buffer + sizeof(buffer);
135 while (p < stop) {
136 *string++ = *p++;
137 }
138 SkASSERT(string - start <= SkStrAppendU32_MaxSize);
139 return string;
140 }
141
SkStrAppendS32(char string[],int32_t dec)142 char* SkStrAppendS32(char string[], int32_t dec) {
143 uint32_t udec = dec;
144 if (dec < 0) {
145 *string++ = '-';
146 udec = ~udec + 1; // udec = -udec, but silences some warnings that are trying to be helpful
147 }
148 return SkStrAppendU32(string, udec);
149 }
150
SkStrAppendU64(char string[],uint64_t dec,int minDigits)151 char* SkStrAppendU64(char string[], uint64_t dec, int minDigits) {
152 SkDEBUGCODE(char* start = string;)
153
154 char buffer[SkStrAppendU64_MaxSize];
155 char* p = buffer + sizeof(buffer);
156
157 do {
158 *--p = SkToU8('0' + (int32_t) (dec % 10));
159 dec /= 10;
160 minDigits--;
161 } while (dec != 0);
162
163 while (minDigits > 0) {
164 *--p = '0';
165 minDigits--;
166 }
167
168 SkASSERT(p >= buffer);
169 size_t cp_len = buffer + sizeof(buffer) - p;
170 memcpy(string, p, cp_len);
171 string += cp_len;
172
173 SkASSERT(string - start <= SkStrAppendU64_MaxSize);
174 return string;
175 }
176
SkStrAppendS64(char string[],int64_t dec,int minDigits)177 char* SkStrAppendS64(char string[], int64_t dec, int minDigits) {
178 uint64_t udec = dec;
179 if (dec < 0) {
180 *string++ = '-';
181 udec = ~udec + 1; // udec = -udec, but silences some warnings that are trying to be helpful
182 }
183 return SkStrAppendU64(string, udec, minDigits);
184 }
185
SkStrAppendFloat(char string[],float value)186 char* SkStrAppendFloat(char string[], float value) {
187 // since floats have at most 8 significant digits, we limit our %g to that.
188 static const char gFormat[] = "%.8g";
189 // make it 1 larger for the terminating 0
190 char buffer[SkStrAppendScalar_MaxSize + 1];
191 int len = SNPRINTF(buffer, sizeof(buffer), gFormat, value);
192 memcpy(string, buffer, len);
193 SkASSERT(len <= SkStrAppendScalar_MaxSize);
194 return string + len;
195 }
196
197 ///////////////////////////////////////////////////////////////////////////////
198
199 const SkString::Rec SkString::gEmptyRec(0, 0);
200
201 #define SizeOfRec() (gEmptyRec.data() - (const char*)&gEmptyRec)
202
trim_size_t_to_u32(size_t value)203 static uint32_t trim_size_t_to_u32(size_t value) {
204 if (sizeof(size_t) > sizeof(uint32_t)) {
205 if (value > SK_MaxU32) {
206 value = SK_MaxU32;
207 }
208 }
209 return (uint32_t)value;
210 }
211
check_add32(size_t base,size_t extra)212 static size_t check_add32(size_t base, size_t extra) {
213 SkASSERT(base <= SK_MaxU32);
214 if (sizeof(size_t) > sizeof(uint32_t)) {
215 if (base + extra > SK_MaxU32) {
216 extra = SK_MaxU32 - base;
217 }
218 }
219 return extra;
220 }
221
Make(const char text[],size_t len)222 sk_sp<SkString::Rec> SkString::Rec::Make(const char text[], size_t len) {
223 if (0 == len) {
224 return sk_sp<SkString::Rec>(const_cast<Rec*>(&gEmptyRec));
225 }
226
227 len = trim_size_t_to_u32(len);
228 // add 1 for terminating 0, then align4 so we can have some slop when growing the string
229 const size_t actualLength = SizeOfRec() + SkAlign4(len + 1);
230 SkASSERT_RELEASE(len < actualLength); // Check for overflow.
231
232 void* storage = ::operator new (actualLength);
233 sk_sp<Rec> rec(new (storage) Rec(SkToU32(len), 1));
234 if (text) {
235 memcpy(rec->data(), text, len);
236 }
237 rec->data()[len] = 0;
238 return rec;
239 }
240
ref() const241 void SkString::Rec::ref() const {
242 if (this == &SkString::gEmptyRec) {
243 return;
244 }
245 SkAssertResult(this->fRefCnt.fetch_add(+1, std::memory_order_relaxed));
246 }
247
unref() const248 void SkString::Rec::unref() const {
249 if (this == &SkString::gEmptyRec) {
250 return;
251 }
252 int32_t oldRefCnt = this->fRefCnt.fetch_add(-1, std::memory_order_acq_rel);
253 SkASSERT(oldRefCnt);
254 if (1 == oldRefCnt) {
255 delete this;
256 }
257 }
258
unique() const259 bool SkString::Rec::unique() const {
260 return fRefCnt.load(std::memory_order_acquire) == 1;
261 }
262
263 #ifdef SK_DEBUG
validate() const264 void SkString::validate() const {
265 // make sure know one has written over our global
266 SkASSERT(0 == gEmptyRec.fLength);
267 SkASSERT(0 == gEmptyRec.fRefCnt.load(std::memory_order_relaxed));
268 SkASSERT(0 == gEmptyRec.data()[0]);
269
270 if (fRec.get() != &gEmptyRec) {
271 SkASSERT(fRec->fLength > 0);
272 SkASSERT(fRec->fRefCnt.load(std::memory_order_relaxed) > 0);
273 SkASSERT(0 == fRec->data()[fRec->fLength]);
274 }
275 }
276 #endif
277
278 ///////////////////////////////////////////////////////////////////////////////
279
SkString()280 SkString::SkString() : fRec(const_cast<Rec*>(&gEmptyRec)) {
281 }
282
SkString(size_t len)283 SkString::SkString(size_t len) {
284 fRec = Rec::Make(nullptr, len);
285 }
286
SkString(const char text[])287 SkString::SkString(const char text[]) {
288 size_t len = text ? strlen(text) : 0;
289
290 fRec = Rec::Make(text, len);
291 }
292
SkString(const char text[],size_t len)293 SkString::SkString(const char text[], size_t len) {
294 fRec = Rec::Make(text, len);
295 }
296
SkString(const SkString & src)297 SkString::SkString(const SkString& src) {
298 src.validate();
299
300 fRec = src.fRec;
301 }
302
SkString(SkString && src)303 SkString::SkString(SkString&& src) {
304 src.validate();
305
306 fRec = std::move(src.fRec);
307 src.fRec.reset(const_cast<Rec*>(&gEmptyRec));
308 }
309
~SkString()310 SkString::~SkString() {
311 this->validate();
312 }
313
equals(const SkString & src) const314 bool SkString::equals(const SkString& src) const {
315 return fRec == src.fRec || this->equals(src.c_str(), src.size());
316 }
317
equals(const char text[]) const318 bool SkString::equals(const char text[]) const {
319 return this->equals(text, text ? strlen(text) : 0);
320 }
321
equals(const char text[],size_t len) const322 bool SkString::equals(const char text[], size_t len) const {
323 SkASSERT(len == 0 || text != nullptr);
324
325 return fRec->fLength == len && !memcmp(fRec->data(), text, len);
326 }
327
operator =(const SkString & src)328 SkString& SkString::operator=(const SkString& src) {
329 this->validate();
330
331 if (fRec != src.fRec) {
332 SkString tmp(src);
333 this->swap(tmp);
334 }
335 return *this;
336 }
337
operator =(SkString && src)338 SkString& SkString::operator=(SkString&& src) {
339 this->validate();
340
341 if (fRec != src.fRec) {
342 this->swap(src);
343 }
344 return *this;
345 }
346
operator =(const char text[])347 SkString& SkString::operator=(const char text[]) {
348 this->validate();
349
350 SkString tmp(text);
351 this->swap(tmp);
352
353 return *this;
354 }
355
reset()356 void SkString::reset() {
357 this->validate();
358 fRec.reset(const_cast<Rec*>(&gEmptyRec));
359 }
360
writable_str()361 char* SkString::writable_str() {
362 this->validate();
363
364 if (fRec->fLength) {
365 if (!fRec->unique()) {
366 fRec = Rec::Make(fRec->data(), fRec->fLength);
367 }
368 }
369 return fRec->data();
370 }
371
set(const char text[])372 void SkString::set(const char text[]) {
373 this->set(text, text ? strlen(text) : 0);
374 }
375
set(const char text[],size_t len)376 void SkString::set(const char text[], size_t len) {
377 len = trim_size_t_to_u32(len);
378 bool unique = fRec->unique();
379 if (0 == len) {
380 this->reset();
381 } else if (unique && len <= fRec->fLength) {
382 // should we resize if len <<<< fLength, to save RAM? (e.g. len < (fLength>>1))?
383 // just use less of the buffer without allocating a smaller one
384 char* p = this->writable_str();
385 if (text) {
386 memcpy(p, text, len);
387 }
388 p[len] = 0;
389 fRec->fLength = SkToU32(len);
390 } else if (unique && (fRec->fLength >> 2) == (len >> 2)) {
391 // we have spare room in the current allocation, so don't alloc a larger one
392 char* p = this->writable_str();
393 if (text) {
394 memcpy(p, text, len);
395 }
396 p[len] = 0;
397 fRec->fLength = SkToU32(len);
398 } else {
399 SkString tmp(text, len);
400 this->swap(tmp);
401 }
402 }
403
setUTF16(const uint16_t src[])404 void SkString::setUTF16(const uint16_t src[]) {
405 int count = 0;
406
407 while (src[count]) {
408 count += 1;
409 }
410 this->setUTF16(src, count);
411 }
412
setUTF16(const uint16_t src[],size_t count)413 void SkString::setUTF16(const uint16_t src[], size_t count) {
414 count = trim_size_t_to_u32(count);
415
416 if (0 == count) {
417 this->reset();
418 } else if (count <= fRec->fLength) {
419 // should we resize if len <<<< fLength, to save RAM? (e.g. len < (fLength>>1))
420 if (count < fRec->fLength) {
421 this->resize(count);
422 }
423 char* p = this->writable_str();
424 for (size_t i = 0; i < count; i++) {
425 p[i] = SkToU8(src[i]);
426 }
427 p[count] = 0;
428 } else {
429 SkString tmp(count); // puts a null terminator at the end of the string
430 char* p = tmp.writable_str();
431
432 for (size_t i = 0; i < count; i++) {
433 p[i] = SkToU8(src[i]);
434 }
435 this->swap(tmp);
436 }
437 }
438
insert(size_t offset,const char text[])439 void SkString::insert(size_t offset, const char text[]) {
440 this->insert(offset, text, text ? strlen(text) : 0);
441 }
442
insert(size_t offset,const char text[],size_t len)443 void SkString::insert(size_t offset, const char text[], size_t len) {
444 if (len) {
445 size_t length = fRec->fLength;
446 if (offset > length) {
447 offset = length;
448 }
449
450 // Check if length + len exceeds 32bits, we trim len
451 len = check_add32(length, len);
452 if (0 == len) {
453 return;
454 }
455
456 /* If we're the only owner, and we have room in our allocation for the insert,
457 do it in place, rather than allocating a new buffer.
458
459 To know we have room, compare the allocated sizes
460 beforeAlloc = SkAlign4(length + 1)
461 afterAlloc = SkAligh4(length + 1 + len)
462 but SkAlign4(x) is (x + 3) >> 2 << 2
463 which is equivalent for testing to (length + 1 + 3) >> 2 == (length + 1 + 3 + len) >> 2
464 and we can then eliminate the +1+3 since that doesn't affec the answer
465 */
466 if (fRec->unique() && (length >> 2) == ((length + len) >> 2)) {
467 char* dst = this->writable_str();
468
469 if (offset < length) {
470 memmove(dst + offset + len, dst + offset, length - offset);
471 }
472 memcpy(dst + offset, text, len);
473
474 dst[length + len] = 0;
475 fRec->fLength = SkToU32(length + len);
476 } else {
477 /* Seems we should use realloc here, since that is safe if it fails
478 (we have the original data), and might be faster than alloc/copy/free.
479 */
480 SkString tmp(fRec->fLength + len);
481 char* dst = tmp.writable_str();
482
483 if (offset > 0) {
484 memcpy(dst, fRec->data(), offset);
485 }
486 memcpy(dst + offset, text, len);
487 if (offset < fRec->fLength) {
488 memcpy(dst + offset + len, fRec->data() + offset,
489 fRec->fLength - offset);
490 }
491
492 this->swap(tmp);
493 }
494 }
495 }
496
insertUnichar(size_t offset,SkUnichar uni)497 void SkString::insertUnichar(size_t offset, SkUnichar uni) {
498 char buffer[kMaxBytesInUTF8Sequence];
499 size_t len = SkUTF8_FromUnichar(uni, buffer);
500
501 if (len) {
502 this->insert(offset, buffer, len);
503 }
504 }
505
insertS32(size_t offset,int32_t dec)506 void SkString::insertS32(size_t offset, int32_t dec) {
507 char buffer[SkStrAppendS32_MaxSize];
508 char* stop = SkStrAppendS32(buffer, dec);
509 this->insert(offset, buffer, stop - buffer);
510 }
511
insertS64(size_t offset,int64_t dec,int minDigits)512 void SkString::insertS64(size_t offset, int64_t dec, int minDigits) {
513 char buffer[SkStrAppendS64_MaxSize];
514 char* stop = SkStrAppendS64(buffer, dec, minDigits);
515 this->insert(offset, buffer, stop - buffer);
516 }
517
insertU32(size_t offset,uint32_t dec)518 void SkString::insertU32(size_t offset, uint32_t dec) {
519 char buffer[SkStrAppendU32_MaxSize];
520 char* stop = SkStrAppendU32(buffer, dec);
521 this->insert(offset, buffer, stop - buffer);
522 }
523
insertU64(size_t offset,uint64_t dec,int minDigits)524 void SkString::insertU64(size_t offset, uint64_t dec, int minDigits) {
525 char buffer[SkStrAppendU64_MaxSize];
526 char* stop = SkStrAppendU64(buffer, dec, minDigits);
527 this->insert(offset, buffer, stop - buffer);
528 }
529
insertHex(size_t offset,uint32_t hex,int minDigits)530 void SkString::insertHex(size_t offset, uint32_t hex, int minDigits) {
531 minDigits = SkTPin(minDigits, 0, 8);
532
533 char buffer[8];
534 char* p = buffer + sizeof(buffer);
535
536 do {
537 *--p = SkHexadecimalDigits::gUpper[hex & 0xF];
538 hex >>= 4;
539 minDigits -= 1;
540 } while (hex != 0);
541
542 while (--minDigits >= 0) {
543 *--p = '0';
544 }
545
546 SkASSERT(p >= buffer);
547 this->insert(offset, p, buffer + sizeof(buffer) - p);
548 }
549
insertScalar(size_t offset,SkScalar value)550 void SkString::insertScalar(size_t offset, SkScalar value) {
551 char buffer[SkStrAppendScalar_MaxSize];
552 char* stop = SkStrAppendScalar(buffer, value);
553 this->insert(offset, buffer, stop - buffer);
554 }
555
printf(const char format[],...)556 void SkString::printf(const char format[], ...) {
557 V_SKSTRING_PRINTF((*this), format);
558 }
559
appendf(const char format[],...)560 void SkString::appendf(const char format[], ...) {
561 char buffer[kBufferSize];
562 int length;
563 ARGS_TO_BUFFER(format, buffer, kBufferSize, length);
564
565 this->append(buffer, length);
566 }
567
appendVAList(const char format[],va_list args)568 void SkString::appendVAList(const char format[], va_list args) {
569 char buffer[kBufferSize];
570 int length = VSNPRINTF(buffer, kBufferSize, format, args);
571 SkASSERT(length >= 0 && length < SkToInt(kBufferSize));
572
573 this->append(buffer, length);
574 }
575
prependf(const char format[],...)576 void SkString::prependf(const char format[], ...) {
577 char buffer[kBufferSize];
578 int length;
579 ARGS_TO_BUFFER(format, buffer, kBufferSize, length);
580
581 this->prepend(buffer, length);
582 }
583
prependVAList(const char format[],va_list args)584 void SkString::prependVAList(const char format[], va_list args) {
585 char buffer[kBufferSize];
586 int length = VSNPRINTF(buffer, kBufferSize, format, args);
587 SkASSERT(length >= 0 && length < SkToInt(kBufferSize));
588
589 this->prepend(buffer, length);
590 }
591
592
593 ///////////////////////////////////////////////////////////////////////////////
594
remove(size_t offset,size_t length)595 void SkString::remove(size_t offset, size_t length) {
596 size_t size = this->size();
597
598 if (offset < size) {
599 if (length > size - offset) {
600 length = size - offset;
601 }
602 SkASSERT(length <= size);
603 SkASSERT(offset <= size - length);
604 if (length > 0) {
605 SkString tmp(size - length);
606 char* dst = tmp.writable_str();
607 const char* src = this->c_str();
608
609 if (offset) {
610 memcpy(dst, src, offset);
611 }
612 size_t tail = size - (offset + length);
613 if (tail) {
614 memcpy(dst + offset, src + (offset + length), tail);
615 }
616 SkASSERT(dst[tmp.size()] == 0);
617 this->swap(tmp);
618 }
619 }
620 }
621
swap(SkString & other)622 void SkString::swap(SkString& other) {
623 this->validate();
624 other.validate();
625
626 SkTSwap(fRec, other.fRec);
627 }
628
629 ///////////////////////////////////////////////////////////////////////////////
630
SkStringPrintf(const char * format,...)631 SkString SkStringPrintf(const char* format, ...) {
632 SkString formattedOutput;
633 V_SKSTRING_PRINTF(formattedOutput, format);
634 return formattedOutput;
635 }
636
SkStrSplit(const char * str,const char * delimiters,SkStrSplitMode splitMode,SkTArray<SkString> * out)637 void SkStrSplit(const char* str, const char* delimiters, SkStrSplitMode splitMode,
638 SkTArray<SkString>* out) {
639 if (splitMode == kCoalesce_SkStrSplitMode) {
640 // Skip any delimiters.
641 str += strspn(str, delimiters);
642 }
643 if (!*str) {
644 return;
645 }
646
647 while (true) {
648 // Find a token.
649 const size_t len = strcspn(str, delimiters);
650 if (splitMode == kStrict_SkStrSplitMode || len > 0) {
651 out->push_back().set(str, len);
652 str += len;
653 }
654
655 if (!*str) {
656 return;
657 }
658 if (splitMode == kCoalesce_SkStrSplitMode) {
659 // Skip any delimiters.
660 str += strspn(str, delimiters);
661 } else {
662 // Skip one delimiter.
663 str += 1;
664 }
665 }
666 }
667
668 #undef VSNPRINTF
669 #undef SNPRINTF
670