Debian Codegraph @

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