SkStringUtils.cpp 2.2 KB

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