1 /*
2 * Copyright 2013 Google Inc.
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 #include "SkString.h"
9 #include "SkStringUtils.h"
10 #include "SkUTF.h"
11
SkAppendScalar(SkString * str,SkScalar value,SkScalarAsStringType asType)12 void SkAppendScalar(SkString* str, SkScalar value, SkScalarAsStringType asType) {
13 switch (asType) {
14 case kHex_SkScalarAsStringType:
15 str->appendf("SkBits2Float(0x%08x)", SkFloat2Bits(value));
16 break;
17 case kDec_SkScalarAsStringType: {
18 SkString tmp;
19 tmp.printf("%g", value);
20 if (tmp.contains('.')) {
21 tmp.appendUnichar('f');
22 }
23 str->append(tmp);
24 break;
25 }
26 }
27 }
28
SkTabString(const SkString & string,int tabCnt)29 SkString SkTabString(const SkString& string, int tabCnt) {
30 if (tabCnt <= 0) {
31 return string;
32 }
33 SkString tabs;
34 for (int i = 0; i < tabCnt; ++i) {
35 tabs.append("\t");
36 }
37 SkString result;
38 static const char newline[] = "\n";
39 const char* input = string.c_str();
40 int nextNL = SkStrFind(input, newline);
41 while (nextNL >= 0) {
42 if (nextNL > 0) {
43 result.append(tabs);
44 }
45 result.append(input, nextNL + 1);
46 input += nextNL + 1;
47 nextNL = SkStrFind(input, newline);
48 }
49 if (*input != '\0') {
50 result.append(tabs);
51 result.append(input);
52 }
53 return result;
54 }
55
SkStringFromUTF16(const uint16_t * src,size_t count)56 SkString SkStringFromUTF16(const uint16_t* src, size_t count) {
57 SkString ret;
58 const uint16_t* stop = src + count;
59 if (count > 0) {
60 SkASSERT(src);
61 size_t n = 0;
62 const uint16_t* end = src + count;
63 for (const uint16_t* ptr = src; ptr < end;) {
64 const uint16_t* last = ptr;
65 SkUnichar u = SkUTF::NextUTF16(&ptr, stop);
66 size_t s = SkUTF::ToUTF8(u);
67 if (n > UINT32_MAX - s) {
68 end = last; // truncate input string
69 break;
70 }
71 n += s;
72 }
73 ret = SkString(n);
74 char* out = ret.writable_str();
75 for (const uint16_t* ptr = src; ptr < end;) {
76 out += SkUTF::ToUTF8(SkUTF::NextUTF16(&ptr, stop), out);
77 }
78 SkASSERT(out == ret.writable_str() + n);
79 }
80 return ret;
81 }
82