Skip to content Search Apps Documentation Source Content Run Reset Eval Playground File Folder Download Copy Actions State String Boolean Number Struct Map Slice Pointer Function Closure Reference Nil Package Type Interface Unknown

Community realm. Read the code first. Community realm, deployed by its author. Read the code before you interact or send coins.

json.gno

4.59 Kb · 160 lines
  1package safe
  2
  3import (
  4	"chain/markdown"
  5	"strconv"
  6	"strings"
  7)
  8
  9// Byte classes as 128-bit bitmaps for the native markdown.MatchCharsetN
 10// (one call checks a whole string at ~0.7 gas per byte; bytes >= 0x80 never
 11// match). jsonSafe: printable ASCII that JSONString copies unchanged (not
 12// '"', '\', '<', '>', '&', DEL). rawSafe: [A-Za-z0-9+/=:;,._-].
 13const (
 14	jsonSafeLo = 0xafffffbb00000000
 15	jsonSafeHi = 0x7fffffffefffffff
 16	rawSafeLo  = 0x2ffff80000000000
 17	rawSafeHi  = 0x07fffffe87fffffe
 18	// jsonFastMin: below this length the byte loop is cheaper than the
 19	// native call.
 20	jsonFastMin = 8
 21)
 22
 23// JSONString returns s as a quoted JSON string. Beyond the mandatory
 24// escapes it also escapes U+2028/U+2029 (RA L-12) and '<', '>', '&', so the
 25// output is safe to inline in HTML as well. Strings that need no escape
 26// (printable ASCII without '"', '\', '<', '>', '&') take a native fast
 27// path; the output is the same.
 28func JSONString(s string) string {
 29	if len(s) >= jsonFastMin && markdown.MatchCharsetN(s, jsonSafeLo, jsonSafeHi, jsonSafeLo, jsonSafeHi, 0, len(s)) {
 30		return "\"" + s + "\""
 31	}
 32	const hexDigits = "0123456789abcdef"
 33	var b strings.Builder
 34	b.WriteByte('"')
 35	for _, r := range s {
 36		switch r {
 37		case '"':
 38			b.WriteString(`\"`)
 39		case '\\':
 40			b.WriteString(`\\`)
 41		case '\n':
 42			b.WriteString(`\n`)
 43		case '\r':
 44			b.WriteString(`\r`)
 45		case '\t':
 46			b.WriteString(`\t`)
 47		case '<', '>', '&', 0x2028, 0x2029:
 48			b.WriteString(`\u`)
 49			b.WriteString(PadHex(int64(r), 4))
 50		default:
 51			if r < 0x20 || r == 0x7f {
 52				b.WriteString(`\u00`)
 53				b.WriteByte(hexDigits[(r>>4)&0xf])
 54				b.WriteByte(hexDigits[r&0xf])
 55				continue
 56			}
 57			b.WriteRune(r)
 58		}
 59	}
 60	b.WriteByte('"')
 61	return b.String()
 62}
 63
 64// PadHex renders n in lowercase hex, zero-padded to width.
 65func PadHex(n int64, width int) string {
 66	s := strconv.FormatInt(n, 16)
 67	if len(s) >= width {
 68		return s
 69	}
 70	return strings.Repeat("0", width-len(s)) + s
 71}
 72
 73// JSONWriter is the single JSON producer of every read API (design
 74// §2.5: reads return primitives or JSON, never positional text). It tracks
 75// commas itself, so callers only describe structure:
 76//
 77//	w := &safe.JSONWriter{}
 78//	w.BeginObject(); w.Key("id"); w.Str("1"); w.EndObject()
 79type JSONWriter struct {
 80	b        strings.Builder
 81	hasItems []bool // one entry per open container
 82	afterKey bool
 83}
 84
 85func (w *JSONWriter) BeginObject() { w.open('{') }
 86func (w *JSONWriter) EndObject()   { w.close('}') }
 87func (w *JSONWriter) BeginArray()  { w.open('[') }
 88func (w *JSONWriter) EndArray()    { w.close(']') }
 89
 90// Key starts an object member; the next value call writes its value.
 91func (w *JSONWriter) Key(k string) {
 92	w.separate()
 93	w.b.WriteString(JSONString(k))
 94	w.b.WriteByte(':')
 95	w.afterKey = true
 96}
 97
 98func (w *JSONWriter) Str(v string) { w.value(JSONString(v)) }
 99func (w *JSONWriter) Int(v int64)  { w.value(strconv.FormatInt(v, 10)) }
100func (w *JSONWriter) Bool(v bool)  { w.value(strconv.FormatBool(v)) }
101
102// Raw writes v verbatim. Only for JSON produced by another JSONWriter.
103func (w *JSONWriter) Raw(v string) { w.value(v) }
104
105// RawStr writes v as a JSON string without escaping. v may only hold
106// [A-Za-z0-9+/=:;,._-] (base64, hex, decimal, a data: URI header), which
107// JSON never escapes; any other byte panics. One native pass instead of a
108// rune loop: a 350 KB data URI costs well under 1M gas (M-4, UP-I1).
109func (w *JSONWriter) RawStr(v string) {
110	if !markdown.MatchCharsetN(v, rawSafeLo, rawSafeHi, rawSafeLo, rawSafeHi, 0, len(v)) {
111		panic("JSONWriter: RawStr value may only hold [A-Za-z0-9+/=:;,._-]")
112	}
113	w.separate()
114	w.b.WriteByte('"')
115	w.b.WriteString(v)
116	w.b.WriteByte('"')
117}
118
119// RawStrField is Key + RawStr.
120func (w *JSONWriter) RawStrField(k, v string) { w.Key(k); w.RawStr(v) }
121
122// StrField and IntField are Key+value shorthands.
123func (w *JSONWriter) StrField(k, v string) { w.Key(k); w.Str(v) }
124func (w *JSONWriter) IntField(k string, v int64) { w.Key(k); w.Int(v) }
125func (w *JSONWriter) BoolField(k string, v bool) { w.Key(k); w.Bool(v) }
126
127func (w *JSONWriter) String() string { return w.b.String() }
128
129func (w *JSONWriter) open(c byte) {
130	w.separate()
131	w.b.WriteByte(c)
132	w.hasItems = append(w.hasItems, false)
133}
134
135func (w *JSONWriter) close(c byte) {
136	if len(w.hasItems) == 0 {
137		panic("JSONWriter: close without open")
138	}
139	w.hasItems = w.hasItems[:len(w.hasItems)-1]
140	w.b.WriteByte(c)
141}
142
143func (w *JSONWriter) value(v string) {
144	w.separate()
145	w.b.WriteString(v)
146}
147
148// separate writes the comma before an item, except right after a key.
149func (w *JSONWriter) separate() {
150	if w.afterKey {
151		w.afterKey = false
152		return
153	}
154	if n := len(w.hasItems); n > 0 {
155		if w.hasItems[n-1] {
156			w.b.WriteByte(',')
157		}
158		w.hasItems[n-1] = true
159	}
160}