numfmt.mx raw
1 package runtime
2
3 // Number and boolean text, shared by the builtin String() methods and by the
4 // structural renderer (type_render.mx).
5 //
6 // The builtin String() bodies live in stringer.mx under the moxie.stringer
7 // build tag; the wasm target compiles identity thunks instead. The renderer
8 // runs on every target, so the formatting itself cannot be tag-gated: it lives
9 // here, untagged, and the tagged methods are one-line delegates.
10
11 import (
12 "strconv"
13
14 "moxielang.dev/pkg/mxutil"
15 )
16
17 func BoolText(b bool) string {
18 if b {
19 return "true"
20 }
21 return "false"
22 }
23
24 func Int64Text(n int64) string {
25 if n == 0 {
26 return "0"
27 }
28 neg := n < 0
29 if neg {
30 n = -n
31 if n < 0 {
32 return "-9223372036854775808"
33 }
34 }
35 buf := []byte{:0:20}
36 for n > 0 {
37 buf = mxutil.Ensure(buf, 1)
38 push(buf, byte('0'+n%10))
39 n /= 10
40 }
41 if neg {
42 buf = mxutil.Ensure(buf, 1)
43 push(buf, '-')
44 }
45 for i, j := int32(0), int32(len(buf)-1); i < j; i, j = i+1, j-1 {
46 buf[i], buf[j] = buf[j], buf[i]
47 }
48 return string(buf)
49 }
50
51 func Uint64Text(n uint64) string {
52 if n == 0 {
53 return "0"
54 }
55 buf := []byte{:0:20}
56 for n > 0 {
57 buf = mxutil.Ensure(buf, 1)
58 push(buf, byte('0'+n%10))
59 n /= 10
60 }
61 for i, j := int32(0), int32(len(buf)-1); i < j; i, j = i+1, j-1 {
62 buf[i], buf[j] = buf[j], buf[i]
63 }
64 return string(buf)
65 }
66
67 func UintptrText(n uintptr) string {
68 if n == 0 {
69 return "0x0"
70 }
71 buf := []byte{:0:18}
72 for n > 0 {
73 d := byte(n & 0xf)
74 if d < 10 {
75 buf = mxutil.Ensure(buf, 1)
76 push(buf, '0'+d)
77 } else {
78 buf = mxutil.Ensure(buf, 1)
79 push(buf, 'a'+d-10)
80 }
81 n >>= 4
82 }
83 for i, j := int32(0), int32(len(buf)-1); i < j; i, j = i+1, j-1 {
84 buf[i], buf[j] = buf[j], buf[i]
85 }
86 return "0x" | string(buf)
87 }
88
89 func Float32Text(v float32) string {
90 return string(strconv.FormatFloat(float64(v), 'g', -1, 32))
91 }
92
93 func Float64Text(v float64) string {
94 return string(strconv.FormatFloat(v, 'g', -1, 64))
95 }
96