Importing Upstream version 4.8.2
[platform/upstream/gcc48.git] / libgo / runtime / go-int-to-string.c
1 /* go-int-to-string.c -- convert an integer to a string in Go.
2
3    Copyright 2009 The Go Authors. All rights reserved.
4    Use of this source code is governed by a BSD-style
5    license that can be found in the LICENSE file.  */
6
7 #include "runtime.h"
8 #include "arch.h"
9 #include "malloc.h"
10
11 String
12 __go_int_to_string (intgo v)
13 {
14   char buf[4];
15   int len;
16   unsigned char *retdata;
17   String ret;
18
19   /* A negative value is not valid UTF-8; turn it into the replacement
20      character.  */
21   if (v < 0)
22     v = 0xfffd;
23
24   if (v <= 0x7f)
25     {
26       buf[0] = v;
27       len = 1;
28     }
29   else if (v <= 0x7ff)
30     {
31       buf[0] = 0xc0 + (v >> 6);
32       buf[1] = 0x80 + (v & 0x3f);
33       len = 2;
34     }
35   else
36     {
37       /* If the value is out of range for UTF-8, turn it into the
38          "replacement character".  */
39       if (v > 0x10ffff)
40         v = 0xfffd;
41       /* If the value is a surrogate pair, which is invalid in UTF-8,
42          turn it into the replacement character.  */
43       if (v >= 0xd800 && v < 0xe000)
44         v = 0xfffd;
45
46       if (v <= 0xffff)
47         {
48           buf[0] = 0xe0 + (v >> 12);
49           buf[1] = 0x80 + ((v >> 6) & 0x3f);
50           buf[2] = 0x80 + (v & 0x3f);
51           len = 3;
52         }
53       else
54         {
55           buf[0] = 0xf0 + (v >> 18);
56           buf[1] = 0x80 + ((v >> 12) & 0x3f);
57           buf[2] = 0x80 + ((v >> 6) & 0x3f);
58           buf[3] = 0x80 + (v & 0x3f);
59           len = 4;
60         }
61     }
62
63   retdata = runtime_mallocgc (len, FlagNoPointers, 1, 0);
64   __builtin_memcpy (retdata, buf, len);
65   ret.str = retdata;
66   ret.len = len;
67
68   return ret;
69 }