runtime: Copy runtime_printf from other Go library.
[gcc.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 "go-string.h"
8 #include "runtime.h"
9 #include "arch.h"
10 #include "malloc.h"
11
12 struct __go_string
13 __go_int_to_string (int v)
14 {
15 char buf[4];
16 int len;
17 unsigned char *retdata;
18 struct __go_string ret;
19
20 if (v <= 0x7f)
21 {
22 buf[0] = v;
23 len = 1;
24 }
25 else if (v <= 0x7ff)
26 {
27 buf[0] = 0xc0 + (v >> 6);
28 buf[1] = 0x80 + (v & 0x3f);
29 len = 2;
30 }
31 else
32 {
33 /* If the value is out of range for UTF-8, turn it into the
34 "replacement character". */
35 if (v > 0x10ffff)
36 v = 0xfffd;
37
38 if (v <= 0xffff)
39 {
40 buf[0] = 0xe0 + (v >> 12);
41 buf[1] = 0x80 + ((v >> 6) & 0x3f);
42 buf[2] = 0x80 + (v & 0x3f);
43 len = 3;
44 }
45 else
46 {
47 buf[0] = 0xf0 + (v >> 18);
48 buf[1] = 0x80 + ((v >> 12) & 0x3f);
49 buf[2] = 0x80 + ((v >> 6) & 0x3f);
50 buf[3] = 0x80 + (v & 0x3f);
51 len = 4;
52 }
53 }
54
55 retdata = runtime_mallocgc (len, FlagNoPointers, 1, 0);
56 __builtin_memcpy (retdata, buf, len);
57 ret.__data = retdata;
58 ret.__length = len;
59
60 return ret;
61 }