package jsontextimport ()// Encoder is a streaming encoder of raw JSON tokens and values. It writes a stream of top-level JSON values,// each followed by a line feed.//// Encoder.WriteToken and Encoder.WriteValue calls may be interleaved. For example, the JSON value//// {"name":"value","array":[null,false,true,3.14159],"object":{"k":"v"}}//// can be written by these calls (ignoring errors)://// e.WriteToken(BeginObject) // {// e.WriteToken(String("name")) // "name"// e.WriteToken(String("value")) // "value"// e.WriteValue(Value(`"array"`)) // "array"// e.WriteToken(BeginArray) // [// e.WriteToken(Null) // null// e.WriteToken(False) // false// e.WriteValue(Value("true")) // true// e.WriteToken(Float(3.14159)) // 3.14159// e.WriteToken(EndArray) // ]// e.WriteValue(Value(`"object"`)) // "object"// e.WriteValue(Value(`{"k":"v"}`)) // {"k":"v"}// e.WriteToken(EndObject) // }//// which is one of many sequences of calls which write it.typeEncoderstruct { e encoder}// encoder is the state of an Encoder.type encoder struct { cfg config st stack vs valueScanner w io.Writer bb *bytes.Buffer// w, whose array the output is appended to buf []byte// the output which is not written to w yet base int64// the offset of buf[0] in the output// derived is the cfg which the options of vs were set from, once derivedOK is set, so that an encoder which // is used again with the same options doesn't set them again. derived config derivedOK bool avail []byte// the buffer of AvailableBuffer, which the output doesn't share maxValue int// the OR of the lengths of the values written since the last reset, which sizes avail// invalid is whether a value which MarshalEncode of the v2 json package was writing failed in an object or an // array which it opened: nothing can be written then, until a Reset. The encoder is kept not ready, so that the // writes, which check that first, go to the paths which report it. invalid bool// attached is whether the encoder was attached by the v2 json package after it was set up ( see // attachEncoder ), which attaches it again without setting it up. attached bool// closedPast is whether the attached encoder was asked to end the object or the array which it is attached // in, which is not its own: the value which it was given the place of fails ( see detachEncoder ). closedPast bool// failErr is the error of a call which failed at the attached encoder ( see textcoder.Fail ). failErr error}// NewEncoder constructs a streaming encoder which writes to w, with the options. It writes its buffer to w when// the buffer is full enough, or when a top-level value is complete.//// If w is a bytes.Buffer, the encoder appends to the buffer directly, without copying the output from a buffer// of its own.func ( io.Writer, ...Options) *Encoder { := new(Encoder) .Reset(, ...)return}// Reset resets the encoder to write to w anew, with the options.func ( *Encoder) ( io.Writer, ...Options) {switch {case == nil:panic("jsontext: invalid nil Encoder")case == nil:panic("jsontext: invalid nil io.Writer") } .e.reset(, )}func ( *encoder) ( io.Writer, []Options) {varconfig// opts may hold the options of e, which Options returned .Apply() .cfg = .init()}// ready reports whether the encoder is set up: its scanner points to its stack.func ( *encoder) () bool { return .vs.st == &.st }// setUp sets up an encoder which is not ready: a zero value, as one with no writer, which keeps its output, as// encoding/json/jsontext takes it, or a copy of an encoder, which takes pointers and arrays of its own: it writes// on its own as a copy of an encoder of encoding/json/jsontext does, and the encoder it was copied from keeps its// state.func ( *encoder) () {if .invalid {return }iflen(.st.levels) == 0 { .init(nil)return } .vs.st = &.st .st.own() .buf = slices.Clone(.buf) // the output which is not written yet, which a flush writes as any output .vs.lines, .vs.scratch, .vs.ro = nil, nil, reorderer{} .avail = make([]byte, 0, cap(.avail)) // of the capacity it had, which a Reset keeps}// writeTokenSetUp is writeToken of an encoder which is not ready, which is set up first.func ( *encoder) ( Token) error {if .invalid {return .failAt(errInvalidNamespace, len(.buf), pointNext) } .setUp()return .writeToken()}// writeValueSetUp is writeValue of an encoder which is not ready, which is set up first.func ( *encoder) ( Value) error {if .invalid {return .failAt(errInvalidNamespace, len(.buf), pointNext) } .setUp()return .writeValue()}// init resets the state of the encoder to write to w, which is nil for none, with the options of e.cfg.func ( *encoder) ( io.Writer) {if .attached { .derivedOK = false// the white space of an attached encoder, which its options don't tell ( see derive ) } .invalid, .attached = false, falseif !.ready() {// a zero value, or a copy, whose arrays are the ones of the encoder it was copied from .st, .buf = stack{}, nil .avail = make([]byte, 0, cap(.avail)) // of the capacity it had, which a Reset keeps .vs.st, .vs.lines, .vs.scratch, .vs.ro = &.st, nil, nil, reorderer{} } .st.reset()if .st.outer != nil { .st.outer = nil// of an attach by the v2 json package }if , := .w.(*bytes.Buffer); { .buf = nil// the array of the bytes.Buffer written before, which stays its own, or of a nil one } .w = .bb, _ = .(*bytes.Buffer) .buf = .buf[:0]if .bb != nil { .buf = .bb.AvailableBuffer() } .base, .maxValue = 0, 0if !.derivedOK || !.cfg.Same(&.derived) { .derive() }// the fields are set one by one: a literal of the scanner would be built in a temporary and copied. := &.vs .write, .keep = true, false .spaced = .vs.ws.multiline || .vs.ws.colon || .vs.ws.comma .run = 0 .wsFrom, .wsEnd = 0, 0if .in != nil || .out != nil { .in, .out = nil, nil }}// derive sets the fields which follow from the options, e.cfg.func ( *encoder) () { := &.vs .ws = whitespaceOf(&.cfg)if .attached {// the output of a method or a function of the v2 json package, which formats the whole output after it: the // encoder writes it compact, as the encoder of the package writes the rest, but reports its options. .ws = whitespace{} } .esc = escapesOf(&.cfg) .validUTF8 = !.cfg.Has(allowInvalidUTF8) .rejectDuplicateNames = !.cfg.Has(allowDuplicateNames) .lazyNames = !.rejectDuplicateNames .decoding = false .final = true .preserve = .cfg.Has(preserveRawStrings) .canonInts = .cfg.Has(canonicalizeRawInts) .canonFlts = .cfg.Has(canonicalizeRawFloats) .reorder = .cfg.Has(reorderRawObjects) .lines = .lines[:0] // the lines of the white space of other options// whitespace may have set the defaults of Multiline in cfg: the options which were given differ from it, and // are derived again. .derived, .derivedOK = .cfg, true}// Options returns the options of the encoder: the ones it was constructed or last reset with, and, for Multiline,// the space after a colon and the indentation it takes if they are not set. They follow a later Reset.func ( *Encoder) () Options {return &.e.cfg}// OutputOffset returns the offset in the output after the last token or value which was written. The encoder// may not have written all of it to the writer yet.func ( *Encoder) () int64 {return .e.base + int64(len(.e.buf))}// AvailableBuffer returns an empty buffer which may have room, to build a Value for the next call of// Encoder.WriteValue://// b := e.AvailableBuffer()// b = append(b, '"')// b = appendString(b, v) // append the string formatting of v// b = append(b, '"')// ... := e.WriteValue(b)//// WriteValue takes a valid JSON value: a Value built as raw bytes takes more care than a Token of a// constructor such as String.func ( *Encoder) () []byte {// a buffer of its own: the room of the output would be written over by the value built in it. Its capacity // is the power of two above the values written, as the one of encoding/json/jsontext.if := 1 << bits.Len(uint(.e.maxValue|63)); cap(.e.avail) < { .e.avail = make([]byte, 0, ) }return .e.avail[:0]}// StackDepth returns the number of the objects and arrays which are open in the output: 0 at the top level,// before any token, after a top-level value and between top-level values, 1 in a top-level object or array, and// so on.func ( *Encoder) () int {if !.e.ready() { .e.setUp() }if .e.st.outer != nil {return .e.st.full().depth() }return .e.st.depth()}// StackIndex returns the kind and the length of the level i of the stack, which is from 0 to// Encoder.StackDepth: KindInvalid for the level 0, KindBeginObject for an object, KindBeginArray for an array.// The length of an object counts its names and values: a complete object has an even length.func ( *Encoder) ( int) (Kind, int64) {if !.e.ready() { .e.setUp() }if .e.st.outer != nil {return .e.st.full().index() }return .e.st.index()}// StackPointer returns a JSON Pointer (RFC 6901) to the last value which was written.func ( *Encoder) () Pointer {if !.e.ready() { .e.setUp() }return .e.st.pointer(pointLast)}// failAt is a SyntacticError at the position pos of the output buffer.func ( *encoder) ( error, int, int) error {return &SyntacticError{ByteOffset: .base + int64(), JSONPointer: .st.pointer(), Err: }}// appendDelim appends the comma or colon and the white space before a token of kind k, for which the grammar// was checked.func ( *encoder) ( []byte, Kind) []byte { := .st.last()if .st.depth() == 0 {return }if .needValue() {// a colon, which is also the delimiter of the offset of an error of an end delimiter there = append(, ':')if .vs.ws.colon { = append(, ' ') }return }if == KindEndObject || == KindEndArray {if .count > 0 && .vs.ws.multiline { = .vs.ws.appendLine(, .st.depth()-1) }return }if .count > 0 { = .vs.ws.appendComma() }if .vs.ws.multiline { = .vs.ws.appendLine(, .st.depth()) }return}// WriteToken writes the next token and advances the write offset.//// The token must fit the grammar: a number where the encoder needs an object name, which is always a string,// or the end of an object where an array ends, is an error. At an invalid token, it reports a SyntacticError,// and the state of the encoder doesn't change: the offset of the error is Encoder.OutputOffset plus the// delimiters and white space which would precede the token.func ( *Encoder) ( Token) error {return .e.writeToken()}func ( *encoder) ( Token) error {if !.ready() {return .writeTokenSetUp() } := .Kind() := .st.last()ifmisplaced(, , .st.depth()) {return .misplacedError(, ) } := .bufswitch {case .vs.spaced: = .appendDelim(, )caselen(.st.levels) == 1 || .count == 0 || == KindEndObject || == KindEndArray:// no delimiter in an output without white space: at the top level, before the first token of a level, // and before an end.case .object && .count&1 == 1: = append(, ':')default: = append(, ',') } := len()varerrorswitch {caseKindNull, KindTrue, KindFalse: = append(, literalOf()...)caseKindBeginObject, KindBeginArray:if := .st.push( == KindBeginObject); != nil {return .failAt(, , pointNext) }if .cfg.Value&stringTag != 0 { .cfg.Value &^= stringTag } .setBuf(append(, byte()))return .endValue()caseKindEndObject, KindEndArray:if .st.depth() == .st.outerDepth {return .closePastError() // the level an attached encoder is in, which misplaced lets through } .st.pop() .setBuf(append(, byte()))return .endValue()caseKindString: , = .appendString(, , .needName())default:if .src == &floatSource { = floatfmt.AppendFloat(, math.Float64frombits(.num), 64) // a finite number, whose kind is KindNumber } else { , = .appendNumberToken(, ) } }if != nil {return } .count++ .setBuf()return .endValue()}// misplaced reports whether a token of kind k doesn't fit the grammar in the innermost level l at depth.func misplaced( *level, Kind, int) bool {switch {caseKindEndObject, KindEndArray:return == 0 || .object != ( == KindEndObject) || .needValue()caseKindInvalid:returntrue }return .needName() && != KindString}// closePastError is the error of the end of the object or the array which an attached encoder is attached in: the// encoder writes nothing more, and the value which it was given the place of fails.func ( *encoder) () error { := .failAt(errEndOfPlace, len(.buf), pointNext) .closedPast, .invalid, .vs.st = true, true, nilreturn}// misplacedError is the error of a token of kind k which is misplaced in the innermost level l.func ( *encoder) ( *level, Kind) error {switch {case == KindInvalid:return .failAt(errInvalidToken, len(.buf)+.delimLen(), pointNext)case != KindEndObject && != KindEndArray:return .failAt(ErrNonStringName, len(.buf)+.delimLen(), pointAt)case .st.depth() == 0 || .object != ( == KindEndObject):return .failAt(errMismatchDelim, len(.buf)+.delimLen(), pointNext) }return .failAt(errMissingValue, len(.buf)+.delimLen(), pointAt)}// delimLen is the length of the delimiter and the white space which precede a token of kind k.func ( *encoder) ( Kind) int {var [64]bytereturnlen(.appendDelim([:0], ))}// appendString appends the string token t, a name of an object if name is set.func ( *encoder) ( []byte, Token, bool) ([]byte, error) { := len()switch .source().form {caseformString:varbool , = appendQuoted(, .str, .vs.esc)if ! && .vs.validUTF8 {return , .failAt(errInvalidUTF8, , pointNext) }if {if && .vs.rejectDuplicateNames && .st.addNewName(readOnlyBytes(.str)) {return , nil// a new name of an object of few names, as most are, without the calls of insertName }return , .insertName(, readOnlyBytes(.str), !) // the name is copied }return , nilcaseformFloat, formFloat32:// NaN or an infinity = append(, '"') = appendFloatText(, math.Float64frombits(.num), 64) = append(, '"')if {return , .insertName(, [+1:len()-1], false) }return , nil } := .raw() , , := scanString(, strModeOf(.vs.validUTF8, false))if != nil {return , .failAt(, , pointNext) } = appendRawString(, , , .vs.esc, .cfg.Has(preserveRawStrings))if {var [64]bytereturn , .insertName(, appendUnquoted([:0], , ), false) }return , nil}// insertName adds a name of the innermost object, written at pos.func ( *encoder) ( int, []byte, bool) error {if { = appendValidUTF8(nil, ) }if !.st.insertName(, .vs.rejectDuplicateNames) { := .st.namePointer()return &SyntacticError{ByteOffset: .base + int64(), JSONPointer: , Err: ErrDuplicateName} }returnnil}// appendNumberToken appends the number token t.func ( *encoder) ( []byte, Token) ([]byte, error) {if .source().form != formRaw {return .appendNumber(), nil } := .raw()if , := scanNumber(); != nil || < len() {return , .failAt(invalidChar([:], placeInNumber), len()+, pointNext) }if .vs.numberKept() {returnappend(, ...), nil }returnappendCanonicalNumber(, ), nil}// flushSize is the size of the output from which it is written before a top-level value is complete: the// buffer of a writer stays about as small as it, unless a token or value is larger.const flushSize = 4 << 10// endValue ends a token or value: after a complete top-level value, a line feed, and the output is written,// as it is when the buffer is large.// setBuf sets the output to b, which was appended to it: a slice of the output itself, if b is in its array, so// that the pointer to the array, which most writes don't change, is not written again with a write barrier while// the GC marks.func ( *encoder) ( []byte) {ifunsafe.SliceData() == unsafe.SliceData(.buf) { .buf = .buf[:len()] } else { .buf = }}func ( *encoder) () error {// it is inlined where the output is kept: in a value, or without a writer, which endOutput writes nothing to.if .w == nil || len(.st.levels) > 1 && len(.buf) <= flushSize {returnnil }return .endOutput()}func ( *encoder) () error {if .st.depth() > 0 {return .flush() }if .w == nil {returnnil// a zero value, which keeps its output without the line feed of a stream }if !.cfg.Has(omitTopLevelNewline) { .buf = append(.buf, '\n') }return .flush()}// flush writes the buffer to the writer.func ( *encoder) () error {if .w == nil || len(.buf) == 0 {returnnil } , := .w.Write(.buf) .base += int64()switch {case .bb != nil:// the room of the buffer is kept at a quarter of its length at least, as encoding/json/jsontext keeps it, // so that the output after it doesn't make the encoder grow it.if := .bb.Available(); < .bb.Len()/4 { .bb.Grow( + 1) } .buf = .bb.AvailableBuffer()case == nil || >= len(.buf):// the output is written, as encoding/json/jsontext takes it where the writer reports no error, whatever n .buf = .buf[:0]case > 0: .buf = .buf[:copy(.buf, .buf[:])] }if != nil {return &ioError{write: true, err: } }returnnil}// WriteValue writes the next raw value and advances the write offset. The encoder checks that the value is// valid, and formats its white space and strings as the options say. With AllowInvalidUTF8, invalid UTF-8 is// mangled as the Unicode replacement character, U+FFFD.//// The value must fit the grammar (see the examples of Encoder.WriteToken). At an invalid value, it reports a// SyntacticError, and the state of the encoder doesn't change: the offset of the error is Encoder.OutputOffset// plus the offset of the error in v.func ( *Encoder) ( Value) error {return .e.writeValue()}func ( *encoder) ( Value) error {if !.ready() {return .writeValueSetUp() } .maxValue |= len()if .bb != nil && overlaps(, .buf[len(.buf):]) {// a value in the free space of the bytes.Buffer, whose output is written over it before it is read = bytes.Clone() } := .st.last()iflen() > 1 && [0] == '"' && !.needName() && .vs.plain() {// a string of ASCII which needs no escape and no check, as most strings which a method writes are, is // written as it is, without the scanner.if , := simpleStringEnd(); && == len() { .setBuf(append(.appendDelim(.buf, KindString), ...)) .count++return .endValue() } } := .Kind() := .needName() := .appendDelim(.buf, ) := len() .vs.out = , := .vs.scan(, 0) = .vs.out .vs.out = nilif != nil {return &SyntacticError{ByteOffset: .base + int64(+.pos), JSONPointer: .ptr, Err: .err} }if < len() {// white space after the value, or an errorif = skipSpace(, ); < len() { .st.last().count--return .failAt(invalidChar([:], placeAfterTopLevel), +, pointAt) } }if { .st.last().count--if != KindString {return .failAt(ErrNonStringName, , pointAt) }// the name, which the scanner wrote, is unquoted from the outputvar [64]byteif := .insertName(, appendUnquoted([:0], [:], strEscaped|strInvalidUTF8), false); != nil {return } .st.last().count++ } .buf = return .endValue()}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.