go-int-to-string.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* go-int-to-string.c -- convert an integer 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 "runtime.h"
  6. #include "arch.h"
  7. #include "malloc.h"
  8. String
  9. __go_int_to_string (intgo v)
  10. {
  11. char buf[4];
  12. int len;
  13. unsigned char *retdata;
  14. String ret;
  15. /* A negative value is not valid UTF-8; turn it into the replacement
  16. character. */
  17. if (v < 0)
  18. v = 0xfffd;
  19. if (v <= 0x7f)
  20. {
  21. buf[0] = v;
  22. len = 1;
  23. }
  24. else if (v <= 0x7ff)
  25. {
  26. buf[0] = 0xc0 + (v >> 6);
  27. buf[1] = 0x80 + (v & 0x3f);
  28. len = 2;
  29. }
  30. else
  31. {
  32. /* If the value is out of range for UTF-8, turn it into the
  33. "replacement character". */
  34. if (v > 0x10ffff)
  35. v = 0xfffd;
  36. /* If the value is a surrogate pair, which is invalid in UTF-8,
  37. turn it into the replacement character. */
  38. if (v >= 0xd800 && v < 0xe000)
  39. v = 0xfffd;
  40. if (v <= 0xffff)
  41. {
  42. buf[0] = 0xe0 + (v >> 12);
  43. buf[1] = 0x80 + ((v >> 6) & 0x3f);
  44. buf[2] = 0x80 + (v & 0x3f);
  45. len = 3;
  46. }
  47. else
  48. {
  49. buf[0] = 0xf0 + (v >> 18);
  50. buf[1] = 0x80 + ((v >> 12) & 0x3f);
  51. buf[2] = 0x80 + ((v >> 6) & 0x3f);
  52. buf[3] = 0x80 + (v & 0x3f);
  53. len = 4;
  54. }
  55. }
  56. retdata = runtime_mallocgc (len, 0, FlagNoScan);
  57. __builtin_memcpy (retdata, buf, len);
  58. ret.str = retdata;
  59. ret.len = len;
  60. return ret;
  61. }