1 /* 2 * Copyright 2016 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 "SkSLUtil.h" 9 10 #ifndef __STDC_FORMAT_MACROS 11 #define __STDC_FORMAT_MACROS 12 #endif 13 #include <cinttypes> 14 #include <locale> 15 #include <sstream> 16 #include <string> 17 18 namespace SkSL { 19 20 SkString to_string(double value) { 21 #ifdef SK_BUILD_FOR_WIN 22 #define SNPRINTF _snprintf 23 #else 24 #define SNPRINTF snprintf 25 #endif 26 #define MAX_DOUBLE_CHARS 25 27 char buffer[MAX_DOUBLE_CHARS]; 28 SkDEBUGCODE(int len = )SNPRINTF(buffer, sizeof(buffer), "%.17g", value); 29 ASSERT(len < MAX_DOUBLE_CHARS); 30 SkString result(buffer); 31 if (!strchr(buffer, '.') && !strchr(buffer, 'e')) { 32 result += ".0"; 33 } 34 return result; 35 #undef SNPRINTF 36 #undef MAX_DOUBLE_CHARS 37 } 38 39 SkString to_string(int32_t value) { 40 return SkStringPrintf("%d", value); 41 } 42 43 SkString to_string(uint32_t value) { 44 return SkStringPrintf("%u", value); 45 } 46 47 SkString to_string(int64_t value) { 48 return SkStringPrintf("%" PRId64, value); 49 } 50 51 SkString to_string(uint64_t value) { 52 return SkStringPrintf("%" PRIu64, value); 53 } 54 55 int stoi(SkString s) { 56 if (s.size() > 2 && s[0] == '0' && s[1] == 'x') { 57 char* p; 58 int result = strtoul(s.c_str() + 2, &p, 16); 59 ASSERT(*p == 0); 60 return result; 61 } 62 return atoi(s.c_str()); 63 } 64 65 double stod(SkString s) { 66 double result; 67 std::string str(s.c_str(), s.size()); 68 std::stringstream buffer(str); 69 buffer.imbue(std::locale::classic()); 70 buffer >> result; 71 return result; 72 } 73 74 long stol(SkString s) { 75 if (s.size() > 2 && s[0] == '0' && s[1] == 'x') { 76 char* p; 77 long result = strtoul(s.c_str() + 2, &p, 16); 78 ASSERT(*p == 0); 79 return result; 80 } 81 return atol(s.c_str()); 82 } 83 84 void sksl_abort() { 85 #ifdef SKIA 86 sk_abort_no_print(); 87 exit(1); 88 #else 89 abort(); 90 #endif 91 } 92 93 void write_data(const SkData& data, SkWStream& out) { 94 out.write(data.data(), data.size()); 95 } 96 97 SkString operator+(const SkString& s, const char* c) { 98 SkString result(s); 99 result += c; 100 return result; 101 } 102 103 SkString operator+(const char* c, const SkString& s) { 104 SkString result(c); 105 result += s; 106 return result; 107 } 108 109 SkString operator+(const SkString& s1, const SkString& s2) { 110 SkString result(s1); 111 result += s2; 112 return result; 113 } 114 115 bool operator==(const SkString& s1, const char* s2) { 116 return !strcmp(s1.c_str(), s2); 117 } 118 119 bool operator!=(const SkString& s1, const char* s2) { 120 return strcmp(s1.c_str(), s2); 121 } 122 123 bool operator!=(const char* s1, const SkString& s2) { 124 return strcmp(s1, s2.c_str()); 125 } 126 } // namespace 127