go-int-array-to-string.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* go-int-array-to-string.c -- convert an array of ints to a string in Go.
  2. Copyright 2009 The Go Authors. All rights reserved.
  3. Use of this source code is governed by a BSD-style
  4. license that can be found in the LICENSE file. */
  5. #include "go-assert.h"
  6. #include "runtime.h"
  7. #include "arch.h"
  8. #include "malloc.h"
  9. String
  10. __go_int_array_to_string (const void* p, intgo len)
  11. {
  12. const int32 *ints;
  13. intgo slen;
  14. intgo i;
  15. unsigned char *retdata;
  16. String ret;
  17. unsigned char *s;
  18. ints = (const int32 *) p;
  19. slen = 0;
  20. for (i = 0; i < len; ++i)
  21. {
  22. int32 v;
  23. v = ints[i];
  24. if (v < 0 || v > 0x10ffff)
  25. v = 0xfffd;
  26. else if (0xd800 <= v && v <= 0xdfff)
  27. v = 0xfffd;
  28. if (v <= 0x7f)
  29. slen += 1;
  30. else if (v <= 0x7ff)
  31. slen += 2;
  32. else if (v <= 0xffff)
  33. slen += 3;
  34. else
  35. slen += 4;
  36. }
  37. retdata = runtime_mallocgc ((uintptr) slen, 0, FlagNoScan);
  38. ret.str = retdata;
  39. ret.len = slen;
  40. s = retdata;
  41. for (i = 0; i < len; ++i)
  42. {
  43. int32 v;
  44. v = ints[i];
  45. /* If V is out of range for UTF-8, substitute the replacement
  46. character. */
  47. if (v < 0 || v > 0x10ffff)
  48. v = 0xfffd;
  49. else if (0xd800 <= v && v <= 0xdfff)
  50. v = 0xfffd;
  51. if (v <= 0x7f)
  52. *s++ = v;
  53. else if (v <= 0x7ff)
  54. {
  55. *s++ = 0xc0 | ((v >> 6) & 0x1f);
  56. *s++ = 0x80 | (v & 0x3f);
  57. }
  58. else if (v <= 0xffff)
  59. {
  60. *s++ = 0xe0 | ((v >> 12) & 0xf);
  61. *s++ = 0x80 | ((v >> 6) & 0x3f);
  62. *s++ = 0x80 | (v & 0x3f);
  63. }
  64. else
  65. {
  66. *s++ = 0xf0 | ((v >> 18) & 0x7);
  67. *s++ = 0x80 | ((v >> 12) & 0x3f);
  68. *s++ = 0x80 | ((v >> 6) & 0x3f);
  69. *s++ = 0x80 | (v & 0x3f);
  70. }
  71. }
  72. __go_assert (s - retdata == slen);
  73. return ret;
  74. }