File: json_writer.go

package info (click to toggle)
golang-golang-x-net 1%3A0.24.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 8,460 kB
  • sloc: asm: 18; makefile: 12; sh: 7
file content (261 lines) | stat: -rw-r--r-- 6,176 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
// Copyright 2023 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build go1.21

package qlog

import (
	"bytes"
	"fmt"
	"io"
	"log/slog"
	"strconv"
	"sync"
	"time"
)

// A jsonWriter writes JSON-SEQ (RFC 7464).
//
// A JSON-SEQ file consists of a series of JSON text records,
// each beginning with an RS (0x1e) character and ending with LF (0x0a).
type jsonWriter struct {
	mu  sync.Mutex
	w   io.WriteCloser
	buf bytes.Buffer
}

// writeRecordStart writes the start of a JSON-SEQ record.
func (w *jsonWriter) writeRecordStart() {
	w.mu.Lock()
	w.buf.WriteByte(0x1e)
	w.buf.WriteByte('{')
}

// writeRecordEnd finishes writing a JSON-SEQ record.
func (w *jsonWriter) writeRecordEnd() {
	w.buf.WriteByte('}')
	w.buf.WriteByte('\n')
	w.w.Write(w.buf.Bytes())
	w.buf.Reset()
	w.mu.Unlock()
}

func (w *jsonWriter) writeAttrs(attrs []slog.Attr) {
	w.buf.WriteByte('{')
	for _, a := range attrs {
		w.writeAttr(a)
	}
	w.buf.WriteByte('}')
}

func (w *jsonWriter) writeAttr(a slog.Attr) {
	if a.Key == "" {
		return
	}
	w.writeName(a.Key)
	w.writeValue(a.Value)
}

// writeAttr writes a []slog.Attr as an object field.
func (w *jsonWriter) writeAttrsField(name string, attrs []slog.Attr) {
	w.writeName(name)
	w.writeAttrs(attrs)
}

func (w *jsonWriter) writeValue(v slog.Value) {
	v = v.Resolve()
	switch v.Kind() {
	case slog.KindAny:
		switch v := v.Any().(type) {
		case []slog.Value:
			w.writeArray(v)
		case interface{ AppendJSON([]byte) []byte }:
			w.buf.Write(v.AppendJSON(w.buf.AvailableBuffer()))
		default:
			w.writeString(fmt.Sprint(v))
		}
	case slog.KindBool:
		w.writeBool(v.Bool())
	case slog.KindDuration:
		w.writeDuration(v.Duration())
	case slog.KindFloat64:
		w.writeFloat64(v.Float64())
	case slog.KindInt64:
		w.writeInt64(v.Int64())
	case slog.KindString:
		w.writeString(v.String())
	case slog.KindTime:
		w.writeTime(v.Time())
	case slog.KindUint64:
		w.writeUint64(v.Uint64())
	case slog.KindGroup:
		w.writeAttrs(v.Group())
	default:
		w.writeString("unhandled kind")
	}
}

// writeName writes an object field name followed by a colon.
func (w *jsonWriter) writeName(name string) {
	if b := w.buf.Bytes(); len(b) > 0 && b[len(b)-1] != '{' {
		// Add the comma separating this from the previous field.
		w.buf.WriteByte(',')
	}
	w.writeString(name)
	w.buf.WriteByte(':')
}

func (w *jsonWriter) writeObject(f func()) {
	w.buf.WriteByte('{')
	f()
	w.buf.WriteByte('}')
}

// writeObject writes an object-valued object field.
// The function f is called to write the contents.
func (w *jsonWriter) writeObjectField(name string, f func()) {
	w.writeName(name)
	w.writeObject(f)
}

func (w *jsonWriter) writeArray(vals []slog.Value) {
	w.buf.WriteByte('[')
	for i, v := range vals {
		if i != 0 {
			w.buf.WriteByte(',')
		}
		w.writeValue(v)
	}
	w.buf.WriteByte(']')
}

func (w *jsonWriter) writeRaw(v string) {
	w.buf.WriteString(v)
}

// writeRawField writes a field with a raw JSON value.
func (w *jsonWriter) writeRawField(name, v string) {
	w.writeName(name)
	w.writeRaw(v)
}

func (w *jsonWriter) writeBool(v bool) {
	if v {
		w.buf.WriteString("true")
	} else {
		w.buf.WriteString("false")
	}
}

// writeBoolField writes a bool-valued object field.
func (w *jsonWriter) writeBoolField(name string, v bool) {
	w.writeName(name)
	w.writeBool(v)
}

// writeDuration writes a duration as milliseconds.
func (w *jsonWriter) writeDuration(v time.Duration) {
	if v < 0 {
		w.buf.WriteByte('-')
		v = -v
	}
	fmt.Fprintf(&w.buf, "%d.%06d", v.Milliseconds(), v%time.Millisecond)
}

// writeDurationField writes a millisecond duration-valued object field.
func (w *jsonWriter) writeDurationField(name string, v time.Duration) {
	w.writeName(name)
	w.writeDuration(v)
}

func (w *jsonWriter) writeFloat64(v float64) {
	w.buf.Write(strconv.AppendFloat(w.buf.AvailableBuffer(), v, 'f', -1, 64))
}

// writeFloat64Field writes an float64-valued object field.
func (w *jsonWriter) writeFloat64Field(name string, v float64) {
	w.writeName(name)
	w.writeFloat64(v)
}

func (w *jsonWriter) writeInt64(v int64) {
	w.buf.Write(strconv.AppendInt(w.buf.AvailableBuffer(), v, 10))
}

// writeInt64Field writes an int64-valued object field.
func (w *jsonWriter) writeInt64Field(name string, v int64) {
	w.writeName(name)
	w.writeInt64(v)
}

func (w *jsonWriter) writeUint64(v uint64) {
	w.buf.Write(strconv.AppendUint(w.buf.AvailableBuffer(), v, 10))
}

// writeUint64Field writes a uint64-valued object field.
func (w *jsonWriter) writeUint64Field(name string, v uint64) {
	w.writeName(name)
	w.writeUint64(v)
}

// writeTime writes a time as seconds since the Unix epoch.
func (w *jsonWriter) writeTime(v time.Time) {
	fmt.Fprintf(&w.buf, "%d.%06d", v.UnixMilli(), v.Nanosecond()%int(time.Millisecond))
}

// writeTimeField writes a time-valued object field.
func (w *jsonWriter) writeTimeField(name string, v time.Time) {
	w.writeName(name)
	w.writeTime(v)
}

func jsonSafeSet(c byte) bool {
	// mask is a 128-bit bitmap with 1s for allowed bytes,
	// so that the byte c can be tested with a shift and an and.
	// If c > 128, then 1<<c and 1<<(c-64) will both be zero,
	// and this function will return false.
	const mask = 0 |
		(1<<(0x22-0x20)-1)<<0x20 |
		(1<<(0x5c-0x23)-1)<<0x23 |
		(1<<(0x7f-0x5d)-1)<<0x5d
	return ((uint64(1)<<c)&(mask&(1<<64-1)) |
		(uint64(1)<<(c-64))&(mask>>64)) != 0
}

func jsonNeedsEscape(s string) bool {
	for i := range s {
		if !jsonSafeSet(s[i]) {
			return true
		}
	}
	return false
}

// writeString writes an ASCII string.
//
// qlog fields should never contain anything that isn't ASCII,
// so we do the bare minimum to avoid producing invalid output if we
// do write something unexpected.
func (w *jsonWriter) writeString(v string) {
	w.buf.WriteByte('"')
	if !jsonNeedsEscape(v) {
		w.buf.WriteString(v)
	} else {
		for i := range v {
			if jsonSafeSet(v[i]) {
				w.buf.WriteByte(v[i])
			} else {
				fmt.Fprintf(&w.buf, `\u%04x`, v[i])
			}
		}
	}
	w.buf.WriteByte('"')
}

// writeStringField writes a string-valued object field.
func (w *jsonWriter) writeStringField(name, v string) {
	w.writeName(name)
	w.writeString(v)
}