Debian Codegraph @

src/encoding/json/jsontext/encode.go

raw
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build goexperiment.jsonv2
6
7 package jsontext
8
9 import (
10 "bytes"
11 "io"
12 "math/bits"
13
14 "encoding/json/internal/jsonflags"
15 "encoding/json/internal/jsonopts"
16 "encoding/json/internal/jsonwire"
17 )
18
19 // Encoder is a streaming encoder from raw JSON tokens and values.
20 // It is used to write a stream of top-level JSON values,
21 // each terminated with a newline character.
22 //
23 // [Encoder.WriteToken] and [Encoder.WriteValue] calls may be interleaved.
24 // For example, the following JSON value:
25 //
26 // {"name":"value","array":[null,false,true,3.14159],"object":{"k":"v"}}
27 //
28 // can be composed with the following calls (ignoring errors for brevity):
29 //
30 // e.WriteToken(BeginObject) // {
31 // e.WriteToken(String("name")) // "name"
32 // e.WriteToken(String("value")) // "value"
33 // e.WriteValue(Value(`"array"`)) // "array"
34 // e.WriteToken(BeginArray) // [
35 // e.WriteToken(Null) // null
36 // e.WriteToken(False) // false
37 // e.WriteValue(Value("true")) // true
38 // e.WriteToken(Float(3.14159)) // 3.14159
39 // e.WriteToken(EndArray) // ]
40 // e.WriteValue(Value(`"object"`)) // "object"
41 // e.WriteValue(Value(`{"k":"v"}`)) // {"k":"v"}
42 // e.WriteToken(EndObject) // }
43 //
44 // The above is one of many possible sequence of calls and
45 // may not represent the most sensible method to call for any given token/value.
46 // For example, it is probably more common to call [Encoder.WriteToken] with a string
47 // for object names.
48 type Encoder struct {
49 s encoderState
50 }
51
52 // encoderState is the low-level state of Encoder.
53 // It has exported fields and method for use by the "json" package.
54 type encoderState struct {
55 state
56 encodeBuffer
57 jsonopts.Struct
58
59 SeenPointers map[any]struct{} // only used when marshaling; identical to json.seenPointers
60 }
61
62 // encodeBuffer is a buffer split into 2 segments:
63 //
64 // - buf[0:len(buf)] // written (but unflushed) portion of the buffer
65 // - buf[len(buf):cap(buf)] // unused portion of the buffer
66 type encodeBuffer struct {
67 Buf []byte // may alias wr if it is a bytes.Buffer
68
69 // baseOffset is added to len(buf) to obtain the absolute offset
70 // relative to the start of io.Writer stream.
71 baseOffset int64
72
73 wr io.Writer
74
75 // maxValue is the approximate maximum Value size passed to WriteValue.
76 maxValue int
77 // availBuffer is the buffer returned by the AvailableBuffer method.
78 availBuffer []byte // always has zero length
79 // bufStats is statistics about buffer utilization.
80 // It is only used with pooled encoders in pools.go.
81 bufStats bufferStatistics
82 }
83
84 // NewEncoder constructs a new streaming encoder writing to w
85 // configured with the provided options.
86 // It flushes the internal buffer when the buffer is sufficiently full or
87 // when a top-level value has been written.
88 //
89 // If w is a [bytes.Buffer], then the encoder appends directly into the buffer
90 // without copying the contents from an intermediate buffer.
91 func NewEncoder(w io.Writer, opts ...Options) *Encoder {
92 e := new(Encoder)
93 e.Reset(w, opts...)
94 return e
95 }
96
97 // Reset resets an encoder such that it is writing afresh to w and
98 // configured with the provided options. Reset must not be called on
99 // a Encoder passed to the [encoding/json/v2.MarshalerTo.MarshalJSONTo] method
100 // or the [encoding/json/v2.MarshalToFunc] function.
101 func (e *Encoder) Reset(w io.Writer, opts ...Options) {
102 switch {
103 case e == nil:
104 panic("jsontext: invalid nil Encoder")
105 case w == nil:
106 panic("jsontext: invalid nil io.Writer")
107 case e.s.Flags.Get(jsonflags.WithinArshalCall):
108 panic("jsontext: cannot reset Encoder passed to json.MarshalerTo")
109 }
110 e.s.reset(nil, w, opts...)
111 }
112
113 func (e *encoderState) reset(b []byte, w io.Writer, opts ...Options) {
114 e.state.reset()
115 e.encodeBuffer = encodeBuffer{Buf: b, wr: w, bufStats: e.bufStats}
116 if bb, ok := w.(*bytes.Buffer); ok && bb != nil {
117 e.Buf = bb.AvailableBuffer() // alias the unused buffer of bb
118 }
119 opts2 := jsonopts.Struct{} // avoid mutating e.Struct in case it is part of opts
120 opts2.Join(opts...)
121 e.Struct = opts2
122 if e.Flags.Get(jsonflags.Multiline) {
123 if !e.Flags.Has(jsonflags.SpaceAfterColon) {
124 e.Flags.Set(jsonflags.SpaceAfterColon | 1)
125 }
126 if !e.Flags.Has(jsonflags.SpaceAfterComma) {
127 e.Flags.Set(jsonflags.SpaceAfterComma | 0)
128 }
129 if !e.Flags.Has(jsonflags.Indent) {
130 e.Flags.Set(jsonflags.Indent | 1)
131 e.Indent = "\t"
132 }
133 }
134 }
135
136 // Options returns the options used to construct the decoder and
137 // may additionally contain semantic options passed to a
138 // [encoding/json/v2.MarshalEncode] call.
139 //
140 // If operating within
141 // a [encoding/json/v2.MarshalerTo.MarshalJSONTo] method call or
142 // a [encoding/json/v2.MarshalToFunc] function call,
143 // then the returned options are only valid within the call.
144 func (e *Encoder) Options() Options {
145 return &e.s.Struct
146 }
147
148 // NeedFlush determines whether to flush at this point.
149 func (e *encoderState) NeedFlush() bool {
150 // NOTE: This function is carefully written to be inlinable.
151
152 // Avoid flushing if e.wr is nil since there is no underlying writer.
153 // Flush if less than 25% of the capacity remains.
154 // Flushing at some constant fraction ensures that the buffer stops growing
155 // so long as the largest Token or Value fits within that unused capacity.
156 return e.wr != nil && (e.Tokens.Depth() == 1 || len(e.Buf) > 3*cap(e.Buf)/4)
157 }
158
159 // Flush flushes the buffer to the underlying io.Writer.
160 // It may append a trailing newline after the top-level value.
161 func (e *encoderState) Flush() error {
162 if e.wr == nil || e.avoidFlush() {
163 return nil
164 }
165
166 // In streaming mode, always emit a newline after the top-level value.
167 if e.Tokens.Depth() == 1 && !e.Flags.Get(jsonflags.OmitTopLevelNewline) {
168 e.Buf = append(e.Buf, '\n')
169 }
170
171 // Inform objectNameStack that we are about to flush the buffer content.
172 e.Names.copyQuotedBuffer(e.Buf)
173
174 // Specialize bytes.Buffer for better performance.
175 if bb, ok := e.wr.(*bytes.Buffer); ok {
176 // If e.buf already aliases the internal buffer of bb,
177 // then the Write call simply increments the internal offset,
178 // otherwise Write operates as expected.
179 // See https://go.dev/issue/42986.
180 n, _ := bb.Write(e.Buf) // never fails unless bb is nil
181 e.baseOffset += int64(n)
182
183 // If the internal buffer of bytes.Buffer is too small,
184 // append operations elsewhere in the Encoder may grow the buffer.
185 // This would be semantically correct, but hurts performance.
186 // As such, ensure 25% of the current length is always available
187 // to reduce the probability that other appends must allocate.
188 if avail := bb.Available(); avail < bb.Len()/4 {
189 bb.Grow(avail + 1)
190 }
191
192 e.Buf = bb.AvailableBuffer()
193 return nil
194 }
195
196 // Flush the internal buffer to the underlying io.Writer.
197 n, err := e.wr.Write(e.Buf)
198 e.baseOffset += int64(n)
199 if err != nil {
200 // In the event of an error, preserve the unflushed portion.
201 // Thus, write errors aren't fatal so long as the io.Writer
202 // maintains consistent state after errors.
203 if n > 0 {
204 e.Buf = e.Buf[:copy(e.Buf, e.Buf[n:])]
205 }
206 return &ioError{action: "write", err: err}
207 }
208 e.Buf = e.Buf[:0]
209
210 // Check whether to grow the buffer.
211 // Note that cap(e.buf) may already exceed maxBufferSize since
212 // an append elsewhere already grew it to store a large token.
213 const maxBufferSize = 4 << 10
214 const growthSizeFactor = 2 // higher value is faster
215 const growthRateFactor = 2 // higher value is slower
216 // By default, grow if below the maximum buffer size.
217 grow := cap(e.Buf) <= maxBufferSize/growthSizeFactor
218 // Growing can be expensive, so only grow
219 // if a sufficient number of bytes have been processed.
220 grow = grow && int64(cap(e.Buf)) < e.previousOffsetEnd()/growthRateFactor
221 if grow {
222 e.Buf = make([]byte, 0, cap(e.Buf)*growthSizeFactor)
223 }
224
225 return nil
226 }
227 func (d *encodeBuffer) offsetAt(pos int) int64 { return d.baseOffset + int64(pos) }
228 func (e *encodeBuffer) previousOffsetEnd() int64 { return e.baseOffset + int64(len(e.Buf)) }
229 func (e *encodeBuffer) unflushedBuffer() []byte { return e.Buf }
230
231 // avoidFlush indicates whether to avoid flushing to ensure there is always
232 // enough in the buffer to unwrite the last object member if it were empty.
233 func (e *encoderState) avoidFlush() bool {
234 switch {
235 case e.Tokens.Last.Length() == 0:
236 // Never flush after BeginObject or BeginArray since we don't know yet
237 // if the object or array will end up being empty.
238 return true
239 case e.Tokens.Last.needObjectValue():
240 // Never flush before the object value since we don't know yet
241 // if the object value will end up being empty.
242 return true
243 case e.Tokens.Last.NeedObjectName() && len(e.Buf) >= 2:
244 // Never flush after the object value if it does turn out to be empty.
245 switch string(e.Buf[len(e.Buf)-2:]) {
246 case `ll`, `""`, `{}`, `[]`: // last two bytes of every empty value
247 return true
248 }
249 }
250 return false
251 }
252
253 // UnwriteEmptyObjectMember unwrites the last object member if it is empty
254 // and reports whether it performed an unwrite operation.
255 func (e *encoderState) UnwriteEmptyObjectMember(prevName *string) bool {
256 if last := e.Tokens.Last; !last.isObject() || !last.NeedObjectName() || last.Length() == 0 {
257 panic("BUG: must be called on an object after writing a value")
258 }
259
260 // The flushing logic is modified to never flush a trailing empty value.
261 // The encoder never writes trailing whitespace eagerly.
262 b := e.unflushedBuffer()
263
264 // Detect whether the last value was empty.
265 var n int
266 if len(b) >= 3 {
267 switch string(b[len(b)-2:]) {
268 case "ll": // last two bytes of `null`
269 n = len(`null`)
270 case `""`:
271 // It is possible for a non-empty string to have `""` as a suffix
272 // if the second to the last quote was escaped.
273 if b[len(b)-3] == '\\' {
274 return false // e.g., `"\""` is not empty
275 }
276 n = len(`""`)
277 case `{}`:
278 n = len(`{}`)
279 case `[]`:
280 n = len(`[]`)
281 }
282 }
283 if n == 0 {
284 return false
285 }
286
287 // Unwrite the value, whitespace, colon, name, whitespace, and comma.
288 b = b[:len(b)-n]
289 b = jsonwire.TrimSuffixWhitespace(b)
290 b = jsonwire.TrimSuffixByte(b, ':')
291 b = jsonwire.TrimSuffixString(b)
292 b = jsonwire.TrimSuffixWhitespace(b)
293 b = jsonwire.TrimSuffixByte(b, ',')
294 e.Buf = b // store back truncated unflushed buffer
295
296 // Undo state changes.
297 e.Tokens.Last.decrement() // for object member value
298 e.Tokens.Last.decrement() // for object member name
299 if !e.Flags.Get(jsonflags.AllowDuplicateNames) {
300 if e.Tokens.Last.isActiveNamespace() {
301 e.Namespaces.Last().removeLast()
302 }
303 }
304 e.Names.clearLast()
305 if prevName != nil {
306 e.Names.copyQuotedBuffer(e.Buf) // required by objectNameStack.replaceLastUnquotedName
307 e.Names.replaceLastUnquotedName(*prevName)
308 }
309 return true
310 }
311
312 // UnwriteOnlyObjectMemberName unwrites the only object member name
313 // and returns the unquoted name.
314 func (e *encoderState) UnwriteOnlyObjectMemberName() string {
315 if last := e.Tokens.Last; !last.isObject() || last.Length() != 1 {
316 panic("BUG: must be called on an object after writing first name")
317 }
318
319 // Unwrite the name and whitespace.
320 b := jsonwire.TrimSuffixString(e.Buf)
321 isVerbatim := bytes.IndexByte(e.Buf[len(b):], '\\') < 0
322 name := string(jsonwire.UnquoteMayCopy(e.Buf[len(b):], isVerbatim))
323 e.Buf = jsonwire.TrimSuffixWhitespace(b)
324
325 // Undo state changes.
326 e.Tokens.Last.decrement()
327 if !e.Flags.Get(jsonflags.AllowDuplicateNames) {
328 if e.Tokens.Last.isActiveNamespace() {
329 e.Namespaces.Last().removeLast()
330 }
331 }
332 e.Names.clearLast()
333 return name
334 }
335
336 // WriteToken writes the next token and advances the internal write offset.
337 //
338 // The provided token kind must be consistent with the JSON grammar.
339 // For example, it is an error to provide a number when the encoder
340 // is expecting an object name (which is always a string), or
341 // to provide an end object delimiter when the encoder is finishing an array.
342 // If the provided token is invalid, then it reports a [SyntacticError] and
343 // the internal state remains unchanged. The offset reported
344 // in [SyntacticError] will be relative to the [Encoder.OutputOffset].
345 func (e *Encoder) WriteToken(t Token) error {
346 return e.s.WriteToken(t)
347 }
348 func (e *encoderState) WriteToken(t Token) error {
349 k := t.Kind()
350 b := e.Buf // use local variable to avoid mutating e in case of error
351
352 // Append any delimiters or optional whitespace.
353 b = e.Tokens.MayAppendDelim(b, k)
354 if e.Flags.Get(jsonflags.AnyWhitespace) {
355 b = e.appendWhitespace(b, k)
356 }
357 pos := len(b) // offset before the token
358
359 // Append the token to the output and to the state machine.
360 var err error
361 switch k {
362 case 'n':
363 b = append(b, "null"...)
364 err = e.Tokens.appendLiteral()
365 case 'f':
366 b = append(b, "false"...)
367 err = e.Tokens.appendLiteral()
368 case 't':
369 b = append(b, "true"...)
370 err = e.Tokens.appendLiteral()
371 case '"':
372 if b, err = t.appendString(b, &e.Flags); err != nil {
373 break
374 }
375 if e.Tokens.Last.NeedObjectName() {
376 if !e.Flags.Get(jsonflags.AllowDuplicateNames) {
377 if !e.Tokens.Last.isValidNamespace() {
378 err = errInvalidNamespace
379 break
380 }
381 if e.Tokens.Last.isActiveNamespace() && !e.Namespaces.Last().insertQuoted(b[pos:], false) {
382 err = wrapWithObjectName(ErrDuplicateName, b[pos:])
383 break
384 }
385 }
386 e.Names.ReplaceLastQuotedOffset(pos) // only replace if insertQuoted succeeds
387 }
388 err = e.Tokens.appendString()
389 case '0':
390 if b, err = t.appendNumber(b, &e.Flags); err != nil {
391 break
392 }
393 err = e.Tokens.appendNumber()
394 case '{':
395 b = append(b, '{')
396 if err = e.Tokens.pushObject(); err != nil {
397 break
398 }
399 e.Names.push()
400 if !e.Flags.Get(jsonflags.AllowDuplicateNames) {
401 e.Namespaces.push()
402 }
403 case '}':
404 b = append(b, '}')
405 if err = e.Tokens.popObject(); err != nil {
406 break
407 }
408 e.Names.pop()
409 if !e.Flags.Get(jsonflags.AllowDuplicateNames) {
410 e.Namespaces.pop()
411 }
412 case '[':
413 b = append(b, '[')
414 err = e.Tokens.pushArray()
415 case ']':
416 b = append(b, ']')
417 err = e.Tokens.popArray()
418 default:
419 err = errInvalidToken
420 }
421 if err != nil {
422 return wrapSyntacticError(e, err, pos, +1)
423 }
424
425 // Finish off the buffer and store it back into e.
426 e.Buf = b
427 if e.NeedFlush() {
428 return e.Flush()
429 }
430 return nil
431 }
432
433 // AppendRaw appends either a raw string (without double quotes) or number.
434 // Specify safeASCII if the string output is guaranteed to be ASCII
435 // without any characters (including '<', '>', and '&') that need escaping,
436 // otherwise this will validate whether the string needs escaping.
437 // The appended bytes for a JSON number must be valid.
438 //
439 // This is a specialized implementation of Encoder.WriteValue
440 // that allows appending directly into the buffer.
441 // It is only called from marshal logic in the "json" package.
442 func (e *encoderState) AppendRaw(k Kind, safeASCII bool, appendFn func([]byte) ([]byte, error)) error {
443 b := e.Buf // use local variable to avoid mutating e in case of error
444
445 // Append any delimiters or optional whitespace.
446 b = e.Tokens.MayAppendDelim(b, k)
447 if e.Flags.Get(jsonflags.AnyWhitespace) {
448 b = e.appendWhitespace(b, k)
449 }
450 pos := len(b) // offset before the token
451
452 var err error
453 switch k {
454 case '"':
455 // Append directly into the encoder buffer by assuming that
456 // most of the time none of the characters need escaping.
457 b = append(b, '"')
458 if b, err = appendFn(b); err != nil {
459 return err
460 }
461 b = append(b, '"')
462
463 // Check whether we need to escape the string and if necessary
464 // copy it to a scratch buffer and then escape it back.
465 isVerbatim := safeASCII || !jsonwire.NeedEscape(b[pos+len(`"`):len(b)-len(`"`)])
466 if !isVerbatim {
467 var err error
468 b2 := append(e.availBuffer, b[pos+len(`"`):len(b)-len(`"`)]...)
469 b, err = jsonwire.AppendQuote(b[:pos], string(b2), &e.Flags)
470 e.availBuffer = b2[:0]
471 if err != nil {
472 return wrapSyntacticError(e, err, pos, +1)
473 }
474 }
475
476 // Update the state machine.
477 if e.Tokens.Last.NeedObjectName() {
478 if !e.Flags.Get(jsonflags.AllowDuplicateNames) {
479 if !e.Tokens.Last.isValidNamespace() {
480 return wrapSyntacticError(e, err, pos, +1)
481 }
482 if e.Tokens.Last.isActiveNamespace() && !e.Namespaces.Last().insertQuoted(b[pos:], isVerbatim) {
483 err = wrapWithObjectName(ErrDuplicateName, b[pos:])
484 return wrapSyntacticError(e, err, pos, +1)
485 }
486 }
487 e.Names.ReplaceLastQuotedOffset(pos) // only replace if insertQuoted succeeds
488 }
489 if err := e.Tokens.appendString(); err != nil {
490 return wrapSyntacticError(e, err, pos, +1)
491 }
492 case '0':
493 if b, err = appendFn(b); err != nil {
494 return err
495 }
496 if err := e.Tokens.appendNumber(); err != nil {
497 return wrapSyntacticError(e, err, pos, +1)
498 }
499 default:
500 panic("BUG: invalid kind")
501 }
502
503 // Finish off the buffer and store it back into e.
504 e.Buf = b
505 if e.NeedFlush() {
506 return e.Flush()
507 }
508 return nil
509 }
510
511 // WriteValue writes the next raw value and advances the internal write offset.
512 // The Encoder does not simply copy the provided value verbatim, but
513 // parses it to ensure that it is syntactically valid and reformats it
514 // according to how the Encoder is configured to format whitespace and strings.
515 // If [AllowInvalidUTF8] is specified, then any invalid UTF-8 is mangled
516 // as the Unicode replacement character, U+FFFD.
517 //
518 // The provided value kind must be consistent with the JSON grammar
519 // (see examples on [Encoder.WriteToken]). If the provided value is invalid,
520 // then it reports a [SyntacticError] and the internal state remains unchanged.
521 // The offset reported in [SyntacticError] will be relative to the
522 // [Encoder.OutputOffset] plus the offset into v of any encountered syntax error.
523 func (e *Encoder) WriteValue(v Value) error {
524 return e.s.WriteValue(v)
525 }
526 func (e *encoderState) WriteValue(v Value) error {
527 e.maxValue |= len(v) // bitwise OR is a fast approximation of max
528
529 k := v.Kind()
530 b := e.Buf // use local variable to avoid mutating e in case of error
531
532 // Append any delimiters or optional whitespace.
533 b = e.Tokens.MayAppendDelim(b, k)
534 if e.Flags.Get(jsonflags.AnyWhitespace) {
535 b = e.appendWhitespace(b, k)
536 }
537 pos := len(b) // offset before the value
538
539 // Append the value the output.
540 var n int
541 n += jsonwire.ConsumeWhitespace(v[n:])
542 b, m, err := e.reformatValue(b, v[n:], e.Tokens.Depth())
543 if err != nil {
544 return wrapSyntacticError(e, err, pos+n+m, +1)
545 }
546 n += m
547 n += jsonwire.ConsumeWhitespace(v[n:])
548 if len(v) > n {
549 err = jsonwire.NewInvalidCharacterError(v[n:], "after top-level value")
550 return wrapSyntacticError(e, err, pos+n, 0)
551 }
552
553 // Append the kind to the state machine.
554 switch k {
555 case 'n', 'f', 't':
556 err = e.Tokens.appendLiteral()
557 case '"':
558 if e.Tokens.Last.NeedObjectName() {
559 if !e.Flags.Get(jsonflags.AllowDuplicateNames) {
560 if !e.Tokens.Last.isValidNamespace() {
561 err = errInvalidNamespace
562 break
563 }
564 if e.Tokens.Last.isActiveNamespace() && !e.Namespaces.Last().insertQuoted(b[pos:], false) {
565 err = wrapWithObjectName(ErrDuplicateName, b[pos:])
566 break
567 }
568 }
569 e.Names.ReplaceLastQuotedOffset(pos) // only replace if insertQuoted succeeds
570 }
571 err = e.Tokens.appendString()
572 case '0':
573 err = e.Tokens.appendNumber()
574 case '{':
575 if err = e.Tokens.pushObject(); err != nil {
576 break
577 }
578 if err = e.Tokens.popObject(); err != nil {
579 panic("BUG: popObject should never fail immediately after pushObject: " + err.Error())
580 }
581 if e.Flags.Get(jsonflags.ReorderRawObjects) {
582 mustReorderObjects(b[pos:])
583 }
584 case '[':
585 if err = e.Tokens.pushArray(); err != nil {
586 break
587 }
588 if err = e.Tokens.popArray(); err != nil {
589 panic("BUG: popArray should never fail immediately after pushArray: " + err.Error())
590 }
591 if e.Flags.Get(jsonflags.ReorderRawObjects) {
592 mustReorderObjects(b[pos:])
593 }
594 }
595 if err != nil {
596 return wrapSyntacticError(e, err, pos, +1)
597 }
598
599 // Finish off the buffer and store it back into e.
600 e.Buf = b
601 if e.NeedFlush() {
602 return e.Flush()
603 }
604 return nil
605 }
606
607 // CountNextDelimWhitespace counts the number of bytes of delimiter and
608 // whitespace bytes assuming the upcoming token is a JSON value.
609 // This method is used for error reporting at the semantic layer.
610 func (e *encoderState) CountNextDelimWhitespace() (n int) {
611 const next = Kind('"') // arbitrary kind as next JSON value
612 delim := e.Tokens.needDelim(next)
613 if delim > 0 {
614 n += len(",") | len(":")
615 }
616 if delim == ':' {
617 if e.Flags.Get(jsonflags.SpaceAfterColon) {
618 n += len(" ")
619 }
620 } else {
621 if delim == ',' && e.Flags.Get(jsonflags.SpaceAfterComma) {
622 n += len(" ")
623 }
624 if e.Flags.Get(jsonflags.Multiline) {
625 if m := e.Tokens.NeedIndent(next); m > 0 {
626 n += len("\n") + len(e.IndentPrefix) + (m-1)*len(e.Indent)
627 }
628 }
629 }
630 return n
631 }
632
633 // appendWhitespace appends whitespace that immediately precedes the next token.
634 func (e *encoderState) appendWhitespace(b []byte, next Kind) []byte {
635 if delim := e.Tokens.needDelim(next); delim == ':' {
636 if e.Flags.Get(jsonflags.SpaceAfterColon) {
637 b = append(b, ' ')
638 }
639 } else {
640 if delim == ',' && e.Flags.Get(jsonflags.SpaceAfterComma) {
641 b = append(b, ' ')
642 }
643 if e.Flags.Get(jsonflags.Multiline) {
644 b = e.AppendIndent(b, e.Tokens.NeedIndent(next))
645 }
646 }
647 return b
648 }
649
650 // AppendIndent appends the appropriate number of indentation characters
651 // for the current nested level, n.
652 func (e *encoderState) AppendIndent(b []byte, n int) []byte {
653 if n == 0 {
654 return b
655 }
656 b = append(b, '\n')
657 b = append(b, e.IndentPrefix...)
658 for ; n > 1; n-- {
659 b = append(b, e.Indent...)
660 }
661 return b
662 }
663
664 // reformatValue parses a JSON value from the start of src and
665 // appends it to the end of dst, reformatting whitespace and strings as needed.
666 // It returns the extended dst buffer and the number of consumed input bytes.
667 func (e *encoderState) reformatValue(dst []byte, src Value, depth int) ([]byte, int, error) {
668 // TODO: Should this update ValueFlags as input?
669 if len(src) == 0 {
670 return dst, 0, io.ErrUnexpectedEOF
671 }
672 switch k := Kind(src[0]).normalize(); k {
673 case 'n':
674 if jsonwire.ConsumeNull(src) == 0 {
675 n, err := jsonwire.ConsumeLiteral(src, "null")
676 return dst, n, err
677 }
678 return append(dst, "null"...), len("null"), nil
679 case 'f':
680 if jsonwire.ConsumeFalse(src) == 0 {
681 n, err := jsonwire.ConsumeLiteral(src, "false")
682 return dst, n, err
683 }
684 return append(dst, "false"...), len("false"), nil
685 case 't':
686 if jsonwire.ConsumeTrue(src) == 0 {
687 n, err := jsonwire.ConsumeLiteral(src, "true")
688 return dst, n, err
689 }
690 return append(dst, "true"...), len("true"), nil
691 case '"':
692 if n := jsonwire.ConsumeSimpleString(src); n > 0 {
693 dst = append(dst, src[:n]...) // copy simple strings verbatim
694 return dst, n, nil
695 }
696 return jsonwire.ReformatString(dst, src, &e.Flags)
697 case '0':
698 if n := jsonwire.ConsumeSimpleNumber(src); n > 0 && !e.Flags.Get(jsonflags.CanonicalizeNumbers) {
699 dst = append(dst, src[:n]...) // copy simple numbers verbatim
700 return dst, n, nil
701 }
702 return jsonwire.ReformatNumber(dst, src, &e.Flags)
703 case '{':
704 return e.reformatObject(dst, src, depth)
705 case '[':
706 return e.reformatArray(dst, src, depth)
707 default:
708 return dst, 0, jsonwire.NewInvalidCharacterError(src, "at start of value")
709 }
710 }
711
712 // reformatObject parses a JSON object from the start of src and
713 // appends it to the end of src, reformatting whitespace and strings as needed.
714 // It returns the extended dst buffer and the number of consumed input bytes.
715 func (e *encoderState) reformatObject(dst []byte, src Value, depth int) ([]byte, int, error) {
716 // Append object begin.
717 if len(src) == 0 || src[0] != '{' {
718 panic("BUG: reformatObject must be called with a buffer that starts with '{'")
719 } else if depth == maxNestingDepth+1 {
720 return dst, 0, errMaxDepth
721 }
722 dst = append(dst, '{')
723 n := len("{")
724
725 // Append (possible) object end.
726 n += jsonwire.ConsumeWhitespace(src[n:])
727 if uint(len(src)) <= uint(n) {
728 return dst, n, io.ErrUnexpectedEOF
729 }
730 if src[n] == '}' {
731 dst = append(dst, '}')
732 n += len("}")
733 return dst, n, nil
734 }
735
736 var err error
737 var names *objectNamespace
738 if !e.Flags.Get(jsonflags.AllowDuplicateNames) {
739 e.Namespaces.push()
740 defer e.Namespaces.pop()
741 names = e.Namespaces.Last()
742 }
743 depth++
744 for {
745 // Append optional newline and indentation.
746 if e.Flags.Get(jsonflags.Multiline) {
747 dst = e.AppendIndent(dst, depth)
748 }
749
750 // Append object name.
751 n += jsonwire.ConsumeWhitespace(src[n:])
752 if uint(len(src)) <= uint(n) {
753 return dst, n, io.ErrUnexpectedEOF
754 }
755 m := jsonwire.ConsumeSimpleString(src[n:])
756 isVerbatim := m > 0
757 if isVerbatim {
758 dst = append(dst, src[n:n+m]...)
759 } else {
760 dst, m, err = jsonwire.ReformatString(dst, src[n:], &e.Flags)
761 if err != nil {
762 return dst, n + m, err
763 }
764 }
765 quotedName := src[n : n+m]
766 if !e.Flags.Get(jsonflags.AllowDuplicateNames) && !names.insertQuoted(quotedName, isVerbatim) {
767 return dst, n, wrapWithObjectName(ErrDuplicateName, quotedName)
768 }
769 n += m
770
771 // Append colon.
772 n += jsonwire.ConsumeWhitespace(src[n:])
773 if uint(len(src)) <= uint(n) {
774 return dst, n, wrapWithObjectName(io.ErrUnexpectedEOF, quotedName)
775 }
776 if src[n] != ':' {
777 err = jsonwire.NewInvalidCharacterError(src[n:], "after object name (expecting ':')")
778 return dst, n, wrapWithObjectName(err, quotedName)
779 }
780 dst = append(dst, ':')
781 n += len(":")
782 if e.Flags.Get(jsonflags.SpaceAfterColon) {
783 dst = append(dst, ' ')
784 }
785
786 // Append object value.
787 n += jsonwire.ConsumeWhitespace(src[n:])
788 if uint(len(src)) <= uint(n) {
789 return dst, n, wrapWithObjectName(io.ErrUnexpectedEOF, quotedName)
790 }
791 dst, m, err = e.reformatValue(dst, src[n:], depth)
792 if err != nil {
793 return dst, n + m, wrapWithObjectName(err, quotedName)
794 }
795 n += m
796
797 // Append comma or object end.
798 n += jsonwire.ConsumeWhitespace(src[n:])
799 if uint(len(src)) <= uint(n) {
800 return dst, n, io.ErrUnexpectedEOF
801 }
802 switch src[n] {
803 case ',':
804 dst = append(dst, ',')
805 if e.Flags.Get(jsonflags.SpaceAfterComma) {
806 dst = append(dst, ' ')
807 }
808 n += len(",")
809 continue
810 case '}':
811 if e.Flags.Get(jsonflags.Multiline) {
812 dst = e.AppendIndent(dst, depth-1)
813 }
814 dst = append(dst, '}')
815 n += len("}")
816 return dst, n, nil
817 default:
818 return dst, n, jsonwire.NewInvalidCharacterError(src[n:], "after object value (expecting ',' or '}')")
819 }
820 }
821 }
822
823 // reformatArray parses a JSON array from the start of src and
824 // appends it to the end of dst, reformatting whitespace and strings as needed.
825 // It returns the extended dst buffer and the number of consumed input bytes.
826 func (e *encoderState) reformatArray(dst []byte, src Value, depth int) ([]byte, int, error) {
827 // Append array begin.
828 if len(src) == 0 || src[0] != '[' {
829 panic("BUG: reformatArray must be called with a buffer that starts with '['")
830 } else if depth == maxNestingDepth+1 {
831 return dst, 0, errMaxDepth
832 }
833 dst = append(dst, '[')
834 n := len("[")
835
836 // Append (possible) array end.
837 n += jsonwire.ConsumeWhitespace(src[n:])
838 if uint(len(src)) <= uint(n) {
839 return dst, n, io.ErrUnexpectedEOF
840 }
841 if src[n] == ']' {
842 dst = append(dst, ']')
843 n += len("]")
844 return dst, n, nil
845 }
846
847 var idx int64
848 var err error
849 depth++
850 for {
851 // Append optional newline and indentation.
852 if e.Flags.Get(jsonflags.Multiline) {
853 dst = e.AppendIndent(dst, depth)
854 }
855
856 // Append array value.
857 n += jsonwire.ConsumeWhitespace(src[n:])
858 if uint(len(src)) <= uint(n) {
859 return dst, n, io.ErrUnexpectedEOF
860 }
861 var m int
862 dst, m, err = e.reformatValue(dst, src[n:], depth)
863 if err != nil {
864 return dst, n + m, wrapWithArrayIndex(err, idx)
865 }
866 n += m
867
868 // Append comma or array end.
869 n += jsonwire.ConsumeWhitespace(src[n:])
870 if uint(len(src)) <= uint(n) {
871 return dst, n, io.ErrUnexpectedEOF
872 }
873 switch src[n] {
874 case ',':
875 dst = append(dst, ',')
876 if e.Flags.Get(jsonflags.SpaceAfterComma) {
877 dst = append(dst, ' ')
878 }
879 n += len(",")
880 idx++
881 continue
882 case ']':
883 if e.Flags.Get(jsonflags.Multiline) {
884 dst = e.AppendIndent(dst, depth-1)
885 }
886 dst = append(dst, ']')
887 n += len("]")
888 return dst, n, nil
889 default:
890 return dst, n, jsonwire.NewInvalidCharacterError(src[n:], "after array value (expecting ',' or ']')")
891 }
892 }
893 }
894
895 // OutputOffset returns the current output byte offset. It gives the location
896 // of the next byte immediately after the most recently written token or value.
897 // The number of bytes actually written to the underlying [io.Writer] may be less
898 // than this offset due to internal buffering effects.
899 func (e *Encoder) OutputOffset() int64 {
900 return e.s.previousOffsetEnd()
901 }
902
903 // AvailableBuffer returns a zero-length buffer with a possible non-zero capacity.
904 // This buffer is intended to be used to populate a [Value]
905 // being passed to an immediately succeeding [Encoder.WriteValue] call.
906 //
907 // Example usage:
908 //
909 // b := d.AvailableBuffer()
910 // b = append(b, '"')
911 // b = appendString(b, v) // append the string formatting of v
912 // b = append(b, '"')
913 // ... := d.WriteValue(b)
914 //
915 // It is the user's responsibility to ensure that the value is valid JSON.
916 func (e *Encoder) AvailableBuffer() []byte {
917 // NOTE: We don't return e.buf[len(e.buf):cap(e.buf)] since WriteValue would
918 // need to take special care to avoid mangling the data while reformatting.
919 // WriteValue can't easily identify whether the input Value aliases e.buf
920 // without using unsafe.Pointer. Thus, we just return a different buffer.
921 // Should this ever alias e.buf, we need to consider how it operates with
922 // the specialized performance optimization for bytes.Buffer.
923 n := 1 << bits.Len(uint(e.s.maxValue|63)) // fast approximation for max length
924 if cap(e.s.availBuffer) < n {
925 e.s.availBuffer = make([]byte, 0, n)
926 }
927 return e.s.availBuffer
928 }
929
930 // StackDepth returns the depth of the state machine for written JSON data.
931 // Each level on the stack represents a nested JSON object or array.
932 // It is incremented whenever an [BeginObject] or [BeginArray] token is encountered
933 // and decremented whenever an [EndObject] or [EndArray] token is encountered.
934 // The depth is zero-indexed, where zero represents the top-level JSON value.
935 func (e *Encoder) StackDepth() int {
936 // NOTE: Keep in sync with Decoder.StackDepth.
937 return e.s.Tokens.Depth() - 1
938 }
939
940 // StackIndex returns information about the specified stack level.
941 // It must be a number between 0 and [Encoder.StackDepth], inclusive.
942 // For each level, it reports the kind:
943 //
944 // - 0 for a level of zero,
945 // - '{' for a level representing a JSON object, and
946 // - '[' for a level representing a JSON array.
947 //
948 // It also reports the length of that JSON object or array.
949 // Each name and value in a JSON object is counted separately,
950 // so the effective number of members would be half the length.
951 // A complete JSON object must have an even length.
952 func (e *Encoder) StackIndex(i int) (Kind, int64) {
953 // NOTE: Keep in sync with Decoder.StackIndex.
954 switch s := e.s.Tokens.index(i); {
955 case i > 0 && s.isObject():
956 return '{', s.Length()
957 case i > 0 && s.isArray():
958 return '[', s.Length()
959 default:
960 return 0, s.Length()
961 }
962 }
963
964 // StackPointer returns a JSON Pointer (RFC 6901) to the most recently written value.
965 func (e *Encoder) StackPointer() Pointer {
966 return Pointer(e.s.AppendStackPointer(nil, -1))
967 }
968
969 func (e *encoderState) AppendStackPointer(b []byte, where int) []byte {
970 e.Names.copyQuotedBuffer(e.Buf)
971 return e.state.appendStackPointer(b, where)
972 }