json.gno
1.45 Kb · 74 lines
1package mimir
2
3import "strings"
4
5const hexDigits = "0123456789abcdef"
6
7// Quote returns s as a JSON string literal.
8func Quote(s string) string {
9 var b strings.Builder
10 b.WriteByte('"')
11 for i := 0; i < len(s); i++ {
12 c := s[i]
13 switch {
14 case c == '"' || c == '\\':
15 b.WriteByte('\\')
16 b.WriteByte(c)
17 case c == '\n':
18 b.WriteString(`\n`)
19 case c == '\r':
20 b.WriteString(`\r`)
21 case c == '\t':
22 b.WriteString(`\t`)
23 case c < 0x20:
24 b.WriteString(`\u00`)
25 b.WriteByte(hexDigits[c>>4])
26 b.WriteByte(hexDigits[c&0xf])
27 default:
28 b.WriteByte(c)
29 }
30 }
31 b.WriteByte('"')
32 return b.String()
33}
34
35// Escape makes user text safe to place in gnoweb markdown: it cannot open
36// links, images, HTML or headings.
37func Escape(s string) string {
38 r := strings.NewReplacer(
39 "\\", "\\\\", "[", "\\[", "]", "\\]", "(", "\\(", ")", "\\)",
40 "<", "<", ">", ">", "*", "\\*", "_", "\\_", "`", "\\`",
41 "#", "\\#", "|", "\\|", "\n", " ", "\r", " ",
42 )
43 return r.Replace(s)
44}
45
46// FormatUSD renders 6-decimal units as a dollar amount with two decimals, rounded down.
47func FormatUSD(units int64) string {
48 sign := ""
49 if units < 0 {
50 sign = "-"
51 units = -units
52 }
53 cents := units / 10_000
54 frac := cents % 100
55 s := sign + itoa(cents/100) + "."
56 if frac < 10 {
57 s += "0"
58 }
59 return s + itoa(frac)
60}
61
62func itoa(n int64) string {
63 if n == 0 {
64 return "0"
65 }
66 var buf [20]byte
67 i := len(buf)
68 for n > 0 {
69 i--
70 buf[i] = byte('0' + n%10)
71 n /= 10
72 }
73 return string(buf[i:])
74}