package encoderimport (stderrors)func ( OpType) () bool {switch {caseOpStructField:returntruecaseOpStructFieldSlice:returntruecaseOpStructFieldArray:returntruecaseOpStructFieldMap:returntruecaseOpStructFieldOmitEmpty:returntruecaseOpStructFieldOmitEmptySlice:returntruecaseOpStructFieldOmitEmptyArray:returntruecaseOpStructFieldOmitEmptyMap:returntruecaseOpStructFieldSlicePtr:returntruecaseOpStructFieldOmitEmptySlicePtr:returntruecaseOpStructFieldArrayPtr:returntruecaseOpStructFieldOmitEmptyArrayPtr:returntruecaseOpStructFieldMapPtr:returntrue }returnfalse}typeOpcodeSetstruct { Type reflect.Type// IfaceIndir is whether a value of Type is stored indirectly in an interface value. // It is decided when the type is compiled, because deciding it is not cheap. IfaceIndir bool// DataWordIsAddr is whether the data word of an interface value of Type is the address of the value // which the opcodes take: the type is stored indirectly, or it is a pointer, which is the address of // the value it points to. DataWordIsAddr bool// Levels is how many levels deeper than the place of the value its opcodes go in their frame ( see // deepestLevel ). Levels uint32// KeyCodes and InterfaceKeyCodes are the opcodes of the value, and of the value held by an interface value, for // each escape of the names of the fields, indexed by the options of KeyEscapeOptions. KeyCodes [4]*Opcode InterfaceKeyCodes [4]*Opcode CodeLength int EndCode *Opcode// Scalar is the opcode of the value if the type is encoded by a single opcode of a scalar ( a number, // a string, a bool, ... ), or nil. Such a value held by an interface value is encoded without a frame. Scalar *Opcode Code Code// queryCache is the opcodes of the field queries of the type, by the hash of the query, which every goroutine // reads without a lock ( see getFilteredCodeSetIfNeeded ). queryCache sync.Map// values is the pool of the values of Type in the heap, which MarshalOf copies its argument to. values sync.Pool// pointee is the opcodes of the value which a pointer of Type points to, or noPointee ( see PointeeOf ). pointee atomic.Pointer[OpcodeSet]}// noPointee is the pointee of the opcodes of a type whose values are not encoded as the values they point to.var noPointee = &OpcodeSet{}// PointeeOf returns the opcodes of the value which a pointer of the type of codeSet points to, if it is stored// indirectly in an interface value, or nil. With functions of marshaling, encoding/json/v2 encodes a pointer at the// top level as the value it points to, addressable, so that the functions are given the value, or the pointer for// the functions of pointers, not the address of the pointer: the pointer, the data word, is the address of the// value for its opcodes. A value stored directly, as a pointer or a map, is encoded by the opcodes of the pointer,// which give the functions of the pointer to it the address of it, as encoding/json/v2 does.func ( *RuntimeContext, *OpcodeSet) *OpcodeSet { := .pointee.Load()if == nil { = noPointeeif := .Type; .Kind() == reflect.Pointer && runtime.IfaceIndir(.Elem()) {if , := pointeeCodeSet(, .Elem()); == nil { = } } .pointee.Store() }if == noPointee {returnnil }return}// ValueShape classifies a type by what a nil data word of an interface value of the type means.typeValueShapeuintconst (// ValueShapePointer is the type whose nil data word is encoded as null: a pointer, a map, ...ValueShapePointerValueShape = iota// ValueShapeAggregate is the type whose nil data word is a value to encode, if the type is stored directly // in an interface value: // - a struct or an array which consists of a single pointer. The pointer is nil, not the value. // - a map which has a marshaler. encoding/json writes null instead of calling the marshaler // only for a nil pointer, so the marshaler of a nil map is called. // - a channel, a function or an unsafe.Pointer, which has no JSON representation, nil or not: its // compile fails, unless the type has a marshaler, which is called.ValueShapeAggregate)// ShapeOf returns the shape of the type given by the pointer to its type descriptor.//// ShapeOf and IfaceIndir are functions of their own, not a part of the VM, and the VM calls them in the// same form as it did before, because any change of the code of the VM changes the register allocation// of the whole VM.////go:noinlinefunc ( unsafe.Pointer) ValueShape {switchruntime.TypeOfPtr().Kind() {casereflect.Struct, reflect.Array, reflect.Chan, reflect.Func, reflect.UnsafePointer:returnValueShapeAggregatecasereflect.Map:// whether the type has a marshaler was decided when the type was compiled. , := compileToGetUnfilteredCodeSet(uintptr(), 0)if != nil {// the VM compiles the type right after this, and it reports the error.returnValueShapeAggregate }switch .Code.Kind() {caseCodeKindMarshalJSON, CodeKindMarshalText:returnValueShapeAggregate } }returnValueShapePointer}// IfaceIndir reports whether a value of the type is stored indirectly in an interface value.// It is decided only once per type, when the type is compiled.////go:noinlinefunc ( unsafe.Pointer) bool { , := compileToGetUnfilteredCodeSet(uintptr(), 0)if != nil {// the VM compiles the type right after this, and it reports the error.returnfalse }return .IfaceIndir}// TakeValue returns the address of a zero value of Type in the heap.//// The runtime context keeps the value of the type it encoded last, because taking one from a sync.Pool costs// as much as a small allocation, and a runtime context is already taken from a pool.func ( *OpcodeSet) ( *RuntimeContext) unsafe.Pointer {if .valueCodeSet == {return .value }if .valueCodeSet != nil { .valueCodeSet.values.Put(.value) } .valueCodeSet = if := .values.Get(); != nil { .value = .(unsafe.Pointer) } else { .value = reflect.New(.Type).UnsafePointer() }return .value}func ( *OpcodeSet) ( string) *OpcodeSet {if , := .queryCache.Load(); {return .(*OpcodeSet) }returnnil}func ( *OpcodeSet) ( string, *OpcodeSet) { .queryCache.Store(, )}typeCompiledCodestruct { Code *Opcode CurLen uintptr NextLen uintptr// Levels is the deepest level which Code goes to in its frame ( see deepestLevel ). Levels uint32// Embedded is whether the recursive struct is embedded in the struct which jumps to it. // The code to jump to is only the fields of the struct then: it has neither the braces nor the check of nil. Embedded bool}// KeyEscapeOptions are the options by which the names of the fields are escaped, whose bits are the index of the// opcodes of each escape ( see OpcodeSet.KeyCodes ): for HTML, and for JavaScript, U+2028 and U+2029.constKeyEscapeOptions = HTMLEscapeOption | NormalizeUTF8Optionvar _ [0]struct{} = [KeyEscapeOptions - 3]struct{}{}// MaxDepth is the deepest nesting of the objects and the arrays which encoding/json and encoding/json/v2 of Go 1.27// take: 10000 levels. The VM checks it where a frame is entered, and where a value of a list is ( see// TailRecursiveFlags ), by the indent of the frame and the deepest level which the opcodes of the frame go to ( see// deepestLevel ). The encoder of a method or a function, and the default representation of a value it declines,// count their levels after the depth of the value ( see RuntimeContext.ValueDepth ). A value which is null, omitted// or empty, as a nil pointer or a nil or empty map or slice, is counted as the levels its type would open, and a raw// value which a method or a function returns is checked by its own depth only ( see AppendRaw ): an output which is// so deep there passes.constMaxDepth = 10000// ErrMaxDepth returns the error of a value nested deeper than MaxDepth, as encoding/json and encoding/json/v2 report// it: an error of the syntax of the output.func ( *RuntimeContext) error {if .Option.Flag&V2Option != 0 {return &errors.TextError{Err: errors.ErrMaxDepth} }returnerrors.ErrSyntax(errors.ErrMaxDepth.Error(), 0)}// StartDetectingCyclesAfter is the number of the frames ( see RuntimeContext.RecursiveLevel ) after which the// values entered, and the maps, are recorded to detect a cycle.//// It is 998, not the 1000 of encoding/json, as it counts frames, not the depth of the JSON value: the top-level value// is written in the frame of the caller, and the check is made before the frame of a value is entered, so the// level is the depth minus 1 there. With 998, the first value recorded is at the depth 1000 and a cycle is found at// the depth 1001, where encoding/json/v2 reports it: its byte offset and JSON pointer are the same.constStartDetectingCyclesAfter = 998// StartDetectingMapCyclesAfter is StartDetectingCyclesAfter for a map ( see RuntimeContext.RecordMap ), whose check// is made in the frame of its value, one level past the check of a frame, which is made before it is entered.constStartDetectingMapCyclesAfter = StartDetectingCyclesAfter + 1// ErrUnsupportedValue returns the error of a cycle through the value at ptr, of the type of code: of the pointer// to it for the opcode of a pointer.func ( *RuntimeContext, *Opcode, unsafe.Pointer) error { := runtime.TypeOfPtr(.Type)if .Op == OpRecursivePtr && .Option.Flag&V2Option != 0 {return &errors.SemanticError{GoType: reflect.PointerTo(), Err: errors.ErrCycle} }returnerrCycle(, , )}// ErrNilMapKey returns the error of a key of a map which is a nil pointer, the operand of code, which has no name// ( see MapKeyFlags ).func ( *Opcode) error {return &errors.UnsupportedValueError{Str: fmt.Sprintf("a nil key of %s", reflect.PointerTo(runtime.TypeOfPtr(.Type)))}}// errCycle returns the error of a cycle through the value at p, of the type typ.func errCycle( *RuntimeContext, reflect.Type, unsafe.Pointer) error {if .Option.Flag&V2Option != 0 {return &errors.SemanticError{GoType: , Err: errors.ErrCycle} }return &errors.UnsupportedValueError{Value: reflect.NewAt(, ).Elem(),Str: fmt.Sprintf("encountered a cycle via %s", ), }}// ErrUnsupportedFloat returns the error of a float which is not finite, the value of the opcode: of encoding/json, with// the float, for v1 and for ReportErrorsWithLegacySemantics.func ( *RuntimeContext, *Opcode, float64) error {if .Option.Flag&(V2Option|ReportErrorsWithLegacySemanticsOption) == V2Option {return &errors.SemanticError{GoType: runtime.TypeOfPtr(.Type), Err: fmt.Errorf("unsupported value: %v", )} }// the value is of the type of the float, which pointers may lead to, as encoding/json gives it := reflect.ValueOf() := runtime.TypeOfPtr(.Type)for .Kind() == reflect.Ptr { = .Elem() }if .Kind() == reflect.Float32 || .Kind() == reflect.Float64 { = reflect.New().Elem() .SetFloat() }return &errors.UnsupportedValueError{Value: ,Str: strconv.FormatFloat(, 'g', -1, 64), }}type emptyInterface struct { typ unsafe.Pointer ptr unsafe.Pointer}// MapItem is a key of a sorted map whose keys are not of a string kind, as it is encoded with a comma after it, and// the index of its entry in the MapContext. While the keys are encoded, Key is the keys from the first one up to the// end of this one, in the output, which tells where it ends ( see MapContext.SortEncodedKeys ).typeMapItemstruct { Key []byte Entry int}typeMapslicestruct { Items []MapItem}// insertionSortMapItems sorts the items by their keys without the last tail bytes of each: the quote which ends// the name, and what follows it. It reports whether two keys have the same name, which are put in order after// ( see sortTiedKeys ).func insertionSortMapItems( []MapItem, int) bool { := falsefor := 1; < len(); ++ {if := bytes.Compare([-1].Key[:len([-1].Key)-], [].Key[:len([].Key)-]); <= 0 {if == 0 { = true }continue } := [] := .Key[:len(.Key)-] := for ; > 0; -- {if := bytes.Compare([-1].Key[:len([-1].Key)-], ); <= 0 {if == 0 { = true }break } [] = [-1] } [] = }return}// sortTiedKeys puts the items of the same name, which are next to each other, in the order of their Go keys// ( see compareTiedKeys ). tail is the length of what follows the names of the keys.func ( *MapContext) ( []MapItem, int) {for := 1; < len(); ++ { := [] := .Key[:len(.Key)-] := for ; > 0 && compareKeyNames([-1].Key[:len([-1].Key)-], ) == 0 && .compareTiedKeys([-1], ) > 0; -- { [] = [-1] } [] = }}// insertionSortMapItemsByNames is insertionSortMapItems for the keys of a map of which one has an escape// ( see compareKeyNames ).func insertionSortMapItemsByNames( []MapItem, int) bool { := falsefor := 1; < len(); ++ { := [] := .Key[:len(.Key)-] := for ; > 0; -- {if := compareKeyNames([-1].Key[:len([-1].Key)-], ); <= 0 {if == 0 { = true }break } [] = [-1] } [] = }return}// compareTiedKeys compares the entries of two keys of the same name, which the keys of the same text have, or of// texts which have invalid UTF-8, replaced in their names: by their Go keys, which the context has, so that a map// is encoded the same way every time. encoding/json leaves their order to the order of the map. A key of a string// kind is compared by its string, and another one by its bytes, which are the same for the same map.func ( *MapContext) (, MapItem) int {if .layout.StringKey {returnstrings.Compare(.Keys[.Entry], .Keys[.Entry]) } := int(.layout.keySize)returnbytes.Compare(.RawKeys[.Entry*:.Entry*+], .RawKeys[.Entry*:.Entry*+])}// compareKeyNames compares the names of two encoded keys of a map, without the quotes which end them: by their// bytes, which are in the order of the names up to the first one which differs, unless it is in an escape, whose// character is not in the order of the escape. The names are decoded as they are compared then// ( see compareEncodedNames ). The codes of a color before the names are the same for every key.func compareKeyNames(, []byte) int { := min(len(), len()) := 0// the bytes which are the same, eight at a time: the first one which differs is the lowest of the word, as it // is loaded.for ; +8 <= ; += 8 {if := binary.LittleEndian.Uint64([:]) ^ binary.LittleEndian.Uint64([:]); != 0 { += bits.TrailingZeros64() / 8break } }for < && [] == [] { ++ }if == {// a name which the other one begins with: the other one has more characters.returnlen() - len() }// an escape at the byte, or before it, which the byte may be in: the bytes before it are the same in a and b. := [] == '\\' || [] == '\\'for := max(-5, 0); < && !; ++ { = [] == '\\' }if {returncompareEncodedNames(, ) }returnint([]) - int([])}// compareEncodedNames compares the names of two encoded keys, the strings after their first quotes, whose escapes// are the ones AppendString writes, decoded as they are compared. What precedes the quote, as the codes of a// color, is not of the name.func compareEncodedNames(, []byte) int { , = [bytes.IndexByte(, '"')+1:], [bytes.IndexByte(, '"')+1:]// ca and cb are the bytes of the characters being compared which are left: of the input, or of the // character an escape is of, in ra or rb.var , [utf8.UTFMax]bytevar , []bytefor {iflen() == 0 {iflen() == 0 {iflen() == 0 && len() == 0 {return0 }return -1 } , = nextNameChar(, &) }iflen() == 0 {iflen() == 0 {return +1 } , = nextNameChar(, &) }if [0] != [0] {returnint([0]) - int([0]) } , = [1:], [1:] }}// nextNameChar returns the bytes of the first character of the encoded name s, decoded into buf if it is an escape,// and the rest of s. The escapes of the encoder are valid.func nextNameChar( []byte, *[utf8.UTFMax]byte) ([]byte, []byte) {if [0] != '\\' || len() == 1 {return [:1], [1:] }switch := [1]; {case'u':iflen() < 6 {return [:1], [1:] } := hexRune([2:6])ifutf16.IsSurrogate() && len() >= 12 && [6] == '\\' && [7] == 'u' {// a character out of the basic plane, as a pair of surrogates.if := utf16.DecodeRune(, hexRune([8:12])); != utf8.RuneError {return [:utf8.EncodeRune([:], )], [12:] } }return [:utf8.EncodeRune([:], )], [6:]case'n': [0] = '\n'case'r': [0] = '\r'case't': [0] = '\t'case'b': [0] = '\b'case'f': [0] = '\f'default: [0] = }return [:1], [2:]}// maxItemsOfInsertionSort is the number of the items up to which the insertion sort is used.// With keys which are random in their content and in their length, it is faster than slices.SortFunc up to// 24 items and slower from 32 items ( BenchmarkVariant_MapSort ).const maxItemsOfInsertionSort = 16// MapContext is what the VM encodes a map from: the entries read from the map ( MapLayout.Collect ), and// the state of the entry being encoded.typeMapContextstruct { layout *MapLayout// Keys are the keys of the entries, for keys of a string kind; RawKeys are the bytes of the keys of another // kind, keySize each; Values are the bytes of the values, valueSize each. The copies of the values may hold // pointers which the GC doesn't see, as the slots of the VM do: the map holds the values while they are // encoded. Keys []string RawKeys []byte Values []byte// Order is the entries sorted by their keys ( SortKeys ), for keys of a string kind; Sorted is whether // the entries are encoded in that order, or in the order of Slice, which is sorted when every key is encoded. Order []int32 prefixes []uint64// the first bytes of the keys as numbers, while they are sorted Sorted bool// DirectEntries is whether the entries of a sorted map are written directly by one call of the VM, up to one // whose value is left to its opcodes, as the entries of a map which is not sorted are written as it is read: // the values are written by one opcode of a scalar, or are of interface{} ( see MapLayout ). DirectEntries bool Len int Idx int// The keys of a sorted map whose keys are not of a string kind are encoded first, and the entries are written in // the order of their names after ( see SortEncodedKeys ): First is where the entries start in the buffer, Slice // has the keys and Buf is where they are copied. First int Slice *Mapslice items []MapItem// what Slice.Items is made of, kept between the maps Buf []byte// what the collector by reflect.MapIter works with: here so that nothing is allocated for a map. iter reflect.MapIter keyIface any valueIface any// names are the names of the keys written, of a map whose keys may have the same name ( see // appendMapKeyName ), if namesKept is set: they are cleared for each map which needs them. names map[string]struct{} namesKept bool// recorded is whether the map is recorded for the detection of cycles ( see RuntimeContext.RecordMap ). recorded bool}// NewMapContext returns the context to encode a map: the runtime context has one for each level of the maps// nested in each other, kept from a call to the next, and refers to it while the VM has it in a slot, which// the GC doesn't see.func ( *RuntimeContext) *MapContext {if .mapDepth == len(.mapContexts) { .mapContexts = append(.mapContexts, &MapContext{Slice: &Mapslice{}}) } := .mapContexts[.mapDepth] .mapDepth++ .Buf = .Buf[:0] .Idx = 0 .Sorted = false .DirectEntries = false// Items is set by SortByEncodedKeys, and tells the VM the entries are put in that order. .Slice.Items = nil .namesKept, .recorded = false, falsereturn}// RecordMap records the map at p of code, which the VM encodes past StartDetectingMapCyclesAfter, in m, for the// detection of cycles, as encoding/json records a map: a cycle through the values of a map, which are copies, has// the map alone as the value which it reaches again. The maps are recorded apart from the values of the frames,// which a map is not compared with.func ( *RuntimeContext) ( *Opcode, unsafe.Pointer, *MapContext) error {ifslices.Contains(.seenMaps, ) { := // the map, whose address is taken here only, which keeps p from escapingreturnerrCycle(, runtime.TypeOfPtr(.Type), unsafe.Pointer(&)) } .seenMaps = append(.seenMaps, ) .recorded = truereturnnil}// ScalarValue is whether the values of the map are written by one opcode of a scalar ( MapLayout.ScalarValue ).func ( *MapContext) () bool {return .layout.ScalarValue}// SortByEncodedKeys makes the context write the entries in the order of their encoded keys, for a sorted map// whose keys are not of a string kind: the VM encodes every key first and keeps it in Slice ( see OpMapValue ).func ( *MapContext) () {ifcap(.items) < .Len { .items = make([]MapItem, .Len) } .Slice.Items = .items[:.Len]}// SortEncodedKeys sorts the keys of a sorted map whose keys are not of a string kind, which the VM has encoded one// after another in b from First, each item with the keys up to the end of its own: they are moved to Buf, and the// output is put back to First, where the entries are written in the order of the names.//// The keys are sorted by their names, as encoding/json sorts them. A key is its name between quotes, with the codes// of a color around it, which are the same for every key: the keys are compared without the quote which ends the// name and what follows it, as a space or a '!' comes before the quote, and without the codes of the color which// end the name of an integer, which is colored within its quotes: footer is their length, which the VM finds from// the opcode of the keys. When a key has an escape,// which is not in the order of its character, the escapes are decoded where the names differ ( see// compareKeyNames ). It is not sort.Sort, which// calls Less and Swap through an interface for every comparison: the maps to encode are small in most cases, and// the sort was a tenth of the time to encode one.func ( *MapContext) ( *RuntimeContext, []byte, int) []byte { .Buf = append(.Buf[:0], [.First:]...) := .Slice.Items := 0for := range { := len([].Key) [].Key = .Buf[::] = }iflen() == 1 { .Sorted = true .Rewrote(.First)return [:.First] } := [0].Key := 1for [len()-] != '"' { ++ } += switch , := bytes.IndexByte(.Buf, '\\') >= 0, len() > maxItemsOfInsertionSort; {case && :// a key with an escape, which is not in the order of its character.slices.SortFunc(, func(, MapItem) int {if := compareKeyNames(.Key[:len(.Key)-], .Key[:len(.Key)-]); != 0 {return }return .compareTiedKeys(, ) })case :ifinsertionSortMapItemsByNames(, ) { .sortTiedKeys(, ) }case :slices.SortFunc(, func(, MapItem) int {if := bytes.Compare(.Key[:len(.Key)-], .Key[:len(.Key)-]); != 0 {return }return .compareTiedKeys(, ) })default:ifinsertionSortMapItems(, ) { .sortTiedKeys(, ) } } .Sorted = true .Rewrote(.First)return [:.First]}// SortedKeysStart returns where the keys of the sorted map whose keys are being encoded start in the output, which// are not entries yet ( see MapContext.SortEncodedKeys ): a method which writes a key sees the output before them.func ( *RuntimeContext) () int {return .mapContexts[.mapDepth-1].First}// appendText appends the text of a marshaler or of the key of a map as a string.func appendText( *RuntimeContext, []byte, string) []byte { , _ = jsonstring.AppendQuoted(StringEscaper(), , )return}func ( *RuntimeContext, *MapContext) {// a map is always released before the maps it is in. .mapDepth--if .recorded {// the last record: the ones of the maps of its values were dropped before .seenMaps = .seenMaps[:len(.seenMaps)-1] }// the keys refer to the map, which the context must not keep alive.clear(.Keys) .Keys = .Keys[:0]}func ( *RuntimeContext, []byte, []byte) []byte {if == nil {ifNilSliceIsEmpty() {returnappend(, `""`...) }returnappend(, `null`...) } := base64.StdEncoding.EncodedLen(len()) = append(, '"') := len() := cap([:])var []byteif > { = [ : +] } else { = make([]byte, ) }base64.StdEncoding.Encode(, )returnappend(append(, ...), '"')}// AppendFloat32 appends v as encoding/json writes a float32: by the shortest decimal which rounds to it, in the// format 'f', or 'e' below 1e-6 and from 1e21, whose exponent has no leading zero.func ( *RuntimeContext, []byte, float32) []byte {returnappendFloatOfBits(, float64(), 32)}// AppendFloat64 appends v as encoding/json writes a float64, as AppendFloat32 does.func ( *RuntimeContext, []byte, float64) []byte {returnappendFloatOfBits(, , 64)}// appendFloatOfBits appends the float of the precision bits, 64 or 32. NaN and the infinities, which the callers// report as errors before, but a map key, are appended as strconv appends them.func appendFloatOfBits( []byte, float64, int) []byte {const = 0x7ff << 52ifmath.Float64bits()& == {returnstrconv.AppendFloat(, , 'g', -1, ) }returnfloatfmt.AppendFloat(, , )}// AppendNumber appends n, which must be a JSON number by its grammar, as encoding/json writes a json.Number: an// empty one as 0.//// A number of up to 24 bytes is copied by the words which overlap, without a call of memmove, and the bytes which// are not digits are found in the words as they are loaded, which the grammar is then checked by, without a call:// an integer at once, and another number by the places of its bytes which are not digits.//// A json.Number is a raw value for the options of encoding/json/v2 which rewrite raw values: they are checked here,// in the function itself, as a call more costs every number.func ( *RuntimeContext, []byte, json.Number) ([]byte, error) {if .Option.Flag&RawRewriteOption != 0 {returnappendRewrittenNumber(, , ) } := len()if == 0 {returnappend(, '0'), nil }if > 24 {if !jsonnum.IsValid(unsafe.Slice(unsafe.StringData(string()), )) {returnnil, invalidNumberError(, false) }returnappend(, ...), nil }ifcap()-len() < { = growForNumber(, ) } := unsafe.Slice(unsafe.StringData(string()), ) := [len() : len()+]// nonDigits has the bit i of each byte i of n which is not a digitvaruintswitch {case > 16: , , := binary.LittleEndian.Uint64(), binary.LittleEndian.Uint64([8:]), binary.LittleEndian.Uint64([-8:])binary.LittleEndian.PutUint64(, )binary.LittleEndian.PutUint64([8:], )binary.LittleEndian.PutUint64([-8:], ) , , := jsonnum.NonDigitTops(), jsonnum.NonDigitTops(), jsonnum.NonDigitTops()if || == 0 && [0] != '0' {return [:len()+], nil } = uint(jsonnum.GatherTops()) | uint(jsonnum.GatherTops())<<8 | uint(jsonnum.GatherTops())<<(-8)case >= 8: , := binary.LittleEndian.Uint64(), binary.LittleEndian.Uint64([-8:])binary.LittleEndian.PutUint64(, )binary.LittleEndian.PutUint64([-8:], ) , := jsonnum.NonDigitTops(), jsonnum.NonDigitTops()if | == 0 && [0] != '0' {return [:len()+], nil } = uint(jsonnum.GatherTops()) | uint(jsonnum.GatherTops())<<(-8)case >= 4: , := binary.LittleEndian.Uint32(), binary.LittleEndian.Uint32([-4:])binary.LittleEndian.PutUint32(, )binary.LittleEndian.PutUint32([-4:], ) := jsonnum.NonDigitTops(uint64() | uint64()<<32)if == 0 && [0] != '0' {return [:len()+], nil } := uint(jsonnum.GatherTops()) = &0xf | >>4<<(-4)default:for := 0; < ; ++ { := [] [] = if -'0' > 9 { |= 1 << } } }// a number without a sign or an exponent, the most common one, firstif &(-1) == 0 {if == 0 {if [0] != '0' || == 1 {return [:len()+], nil } } elseif := bits.TrailingZeros(); [] == '.' && > 0 && < -1 && ([0] != '0' || == 1) {return [:len()+], nil } }// the others by the grammar in place: the bytes which are not digits are a sign, a decimal point, the exponent // and its sign, each at most once and in its place, whose bits are cleared one by one. := 0if [0] == '-' { &^= 1 = 1 } := falseif < && &(1<<) == 0 && ([] != '0' || +1 == || &(1<<(+1)) != 0) { = == 0 , := bits.TrailingZeros(), true// digits after the decimal point, if there is oneif ! && [] == '.' { = +1 < && &(1<<(+1)) == 0 &^= 1 << = && == 0 = bits.TrailingZeros() }if ! && && != 0 && []|0x20 == 'e' { &^= 1 << if +1 < && ([+1] == '+' || [+1] == '-') { &^= 1 << ( + 1) ++ } = +1 < && == 0 } }if ! {returnnil, invalidNumberError(, false) }return [:len()+], nil}// AppendNumberString is AppendNumber of a json.Number of a field with the option string, which the caller// quotes: its error shows the number quoted, as encoding/json shows it.func ( *RuntimeContext, []byte, json.Number) ([]byte, error) {if .Option.Flag&RawRewriteOption != 0 {// a number in a string, which the options which rewrite raw values don't rewrite.returnappendNumberAsIs(, ) } , := AppendNumber(, , )if != nil {returnnil, invalidNumberError(, true) }return , nil}// appendRewrittenNumber is AppendNumber of a json.Number which the options of encoding/json/v2 which rewrite raw// values rewrite, as it is a raw value for them.////go:noinlinefunc appendRewrittenNumber( *RuntimeContext, []byte, json.Number) ([]byte, error) {if == "" { = "0" } := unsafe.Slice(unsafe.StringData(string()), len())if !jsonnum.IsValid() {returnnil, invalidNumberError(, false) }returnV2Hooks.FormatRaw(, , )}// appendNumberAsIs is AppendNumberString of a number which the options which rewrite raw values don't rewrite.////go:noinlinefunc appendNumberAsIs( []byte, json.Number) ([]byte, error) {if == "" {returnappend(, '0'), nil }if !jsonnum.IsValid(unsafe.Slice(unsafe.StringData(string()), len())) {returnnil, invalidNumberError(, true) }returnappend(, ...), nil}// growForNumber returns b with room for n bytes more, growing as append does.////go:noinlinefunc growForNumber( []byte, int) []byte { := make([]byte, len(), 2*cap()+)copy(, )return}// addrForMarshaler returns the pointer to the value held by v, to call a marshaler with a pointer receiver.//// The VM makes v from the address of the value ( interfaceOf ), so the data word of v is that address for every// type, also for a type which is stored directly in an interface value, whose data word is then not the value:// the marshaler is called with the original value, as encoding/json calls it for an addressable value, and// nothing is allocated.func addrForMarshaler( any, reflect.Value) reflect.Value {returnreflect.NewAt(.Type(), (*emptyInterface)(unsafe.Pointer(&)).ptr)}// errStoppedByInvalidUTF8 stops an encoding which wrote a string of invalid UTF-8, whose error is the one of the// string ( see RuntimeContext.InvalidUTF8Output ).var errStoppedByInvalidUTF8 = stderrors.New("stopped by invalid UTF-8")// appendValue appends the value at p by the function of m. An encoding which wrote a string of invalid UTF-8 goes// on to its end, or to the next function, which is not called: a method or a function of marshaling is not called// after the error, as it isn't by encoding/json/v2.func appendValue( *RuntimeContext, *MarshalerCall, []byte, unsafe.Pointer) ([]byte, error) {if .Option.Flag&RejectInvalidUTF8Option != 0 && .HasInvalidUTF8() {return , errStoppedByInvalidUTF8 }return .appendValue(, , )}// appendV2MarshalJSON appends the output of MarshalJSON of the v2 semantics of the value at p, which it calls by// its code, without the call of the function value of m ( see MarshalerCall.v2Raw ), as appendValue does after// m.appendOutput, which AppendMarshalJSON looked at.func appendV2MarshalJSON( *RuntimeContext, *MarshalerCall, []byte, unsafe.Pointer) ([]byte, error) {if .Option.Flag&RejectInvalidUTF8Option != 0 && .HasInvalidUTF8() {return , errStoppedByInvalidUTF8 } , := .call()returnappendV2Raw(, .recv, , , )}// AppendMarshalJSON appends what MarshalJSON of the value returns, compacted. p is the data word of the// interface value of the type of the opcode: the address of the value, or the pointer for a pointer type.func ( *RuntimeContext, *Opcode, []byte, unsafe.Pointer) ([]byte, error) { := .Marshalerif == nil {returnappendMarshalJSONByInterface(, , , interfaceOf(, )) }// a function of the v2 semantics has neither nilIsNull nor, but for MarshalJSON, appendOutput.if .nilIsNull && == nil {returnAppendNull(, ), nil }if .appendOutput != nil {// the output of a type of the standard library is valid and compact: it is written as it is.if , := .appendOutput(, ); {return , nil } }var []bytevarerrorif .Flags&(MarshalerContextFlags|MarshalerFuncFlags) != 0 {// the calls of a context, of MarshalJSONTo and of the v2 semantics, which the others don't look at.switch {case .Flags&MarshalerFuncFlags == 0: := .marshalerContext()if .Option.Flag&FieldQueryOption != 0 { = SetFieldQueryToContext(, .FieldQuery) } , = .callContext(, )case .marshalTo != nil:// its error is the one of MarshalJSONTo, or of the value it declined .ValueDepth = .BaseIndent + .Indentvarboolif , , = .marshalTo(, , ); != nil || {return , }case .v2Raw:returnappendV2MarshalJSON(, , , )default: .ValueDepth = .BaseIndent + .IndentreturnappendValue(, , , ) } } else { , = .call() }if != nil {returnnil, &errors.MarshalerError{Type: .recv, Err: } } := (.Option.Flag & HTMLEscapeOption) != 0if , := appendCompactOutput(, , , .trusted); {// the output is compact and valid: it is copied as it is.return , nil } , := appendCompacted(, , , )if != nil {returnnil, &errors.MarshalerError{Type: .recv, Err: } }return , nil}// interfaceOf returns the interface value of the type of the opcode whose data word is p.func interfaceOf( *Opcode, unsafe.Pointer) any {return *(*any)(unsafe.Pointer(&emptyInterface{typ: .Type, ptr: }))}func appendMarshalJSONByInterface( *RuntimeContext, *Opcode, []byte, any) ([]byte, error) { := reflect.ValueOf() // convert by dynamic interface typeif (.Flags & AddrForMarshalerFlags) != 0 { = addrForMarshaler(, ) }if .Kind() == reflect.Ptr && .IsNil() {returnAppendNull(, ), nil } = .Interface()var []byteif (.Flags & MarshalerContextFlags) != 0 { , := .(marshalerContext)if ! {returnAppendNull(, ), nil } := .marshalerContext()if .Option.Flag&FieldQueryOption != 0 { = SetFieldQueryToContext(, .FieldQuery) } , := .MarshalJSON()if != nil {returnnil, &errors.MarshalerError{Type: reflect.TypeOf(), Err: } } = } else { , := .(json.Marshaler)if ! {returnAppendNull(, ), nil } , := .MarshalJSON()if != nil {returnnil, &errors.MarshalerError{Type: reflect.TypeOf(), Err: } } = } , := appendCompact(, , , (.Option.Flag&HTMLEscapeOption) != 0)if != nil {returnnil, &errors.MarshalerError{Type: reflect.TypeOf(), Err: } }return , nil}func ( *RuntimeContext, *Opcode, []byte, unsafe.Pointer) ([]byte, error) { := .Marshalerif == nil {returnappendMarshalJSONIndentByInterface(, , , interfaceOf(, )) }if .nilIsNull && == nil {returnAppendNull(, ), nil }if .appendOutput != nil {// the output of a type of the standard library is one token, which has nothing to indent.if , := .appendOutput(, ); {return , nil } }var []bytevarerrorswitch {case .marshalTo != nil:// its error is the one of MarshalJSONTo, or of the value it declined .ValueDepth = .BaseIndent + .Indentvarboolif , , = .marshalTo(, , ); != nil || {return , }case (.Flags & MarshalerContextFlags) != 0: , = .callContext(, .marshalerContext())default: , = .call() }if != nil {returnnil, &errors.MarshalerError{Type: .recv, Err: } }returnappendIndentedMarshalJSON(, , , )}func appendMarshalJSONIndentByInterface( *RuntimeContext, *Opcode, []byte, any) ([]byte, error) { := reflect.ValueOf() // convert by dynamic interface typeif (.Flags & AddrForMarshalerFlags) != 0 { = addrForMarshaler(, ) }// a nil pointer is null, as encoding/json does. The VM gives the address of the pointer, // so it is not known to be nil until here.if .Kind() == reflect.Ptr && .IsNil() {returnAppendNull(, ), nil } = .Interface()var []byteif (.Flags & MarshalerContextFlags) != 0 { , := .(marshalerContext)if ! {returnAppendNull(, ), nil } , := .MarshalJSON(.marshalerContext())if != nil {returnnil, &errors.MarshalerError{Type: reflect.TypeOf(), Err: } } = } else { , := .(json.Marshaler)if ! {returnAppendNull(, ), nil } , := .MarshalJSON()if != nil {returnnil, &errors.MarshalerError{Type: reflect.TypeOf(), Err: } } = }returnappendIndentedMarshalJSON(, , , )}func appendIndentedMarshalJSON( *RuntimeContext, *Opcode, []byte, []byte) ([]byte, error) { , := appendIndent( , , ,string(.Prefix)+strings.Repeat(string(.IndentStr), int(.BaseIndent+.Indent)),string(.IndentStr), (.Option.Flag&HTMLEscapeOption) != 0,false, )if != nil {returnnil, &errors.MarshalerError{Type: runtime.TypeOfPtr(.Type), Err: } }return , nil}// AppendMarshalText appends what MarshalText of the value returns, as a string. p is the data word of the// interface value of the type of the opcode: the address of the value, or the pointer for a pointer type.func ( *RuntimeContext, *Opcode, []byte, unsafe.Pointer) ([]byte, error) { := .Marshalerif == nil {if .Flags&InterfaceMapKeyFlags != 0 {returnappendInterfaceMapKey(, , , ) }returnappendMarshalTextByInterface(, , , interfaceOf(, )) }if .nilIsNull && == nil {returnappendNilText(, , ), nil }var []byte := falseif .appendOutput != nil {// the text of a type of the standard library is appended to a buffer of the context, not allocated. , = .appendOutput(.MarshalBuf[:0], )if { .MarshalBuf = } }if ! {varerrorif , = .call(); != nil {returnnil, errors.ErrMarshaler(.recv, , "MarshalText") } }// appendText, written here: it is not inlined, and this is the text of the key of most maps of texts. , _ = jsonstring.AppendQuoted(StringEscaper(), , *(*string)(unsafe.Pointer(&)))return , nil}func appendMarshalTextByInterface( *RuntimeContext, *Opcode, []byte, any) ([]byte, error) { := reflect.ValueOf() // convert by dynamic interface typeif (.Flags & AddrForMarshalerFlags) != 0 { = addrForMarshaler(, ) }// a nil pointer is null, or "" as the name of a key, as encoding/json does. The VM gives the address of // the pointer, so it is not known to be nil until here.if .Kind() == reflect.Ptr && .IsNil() {returnappendNilText(, , ), nil } = .Interface() , := .(encoding.TextMarshaler)if ! {returnAppendNull(, ), nil } , := .MarshalText()if != nil {returnnil, errors.ErrMarshaler(reflect.TypeOf(), , "MarshalText") }returnappendText(, , *(*string)(unsafe.Pointer(&))), nil}// appendNilText appends the text of a nil pointer: null, or "" as the name of a key of a map, as// encoding/json writes them.func appendNilText( *RuntimeContext, *Opcode, []byte) []byte {if .Flags&MapKeyFlags != 0 {returnappend(, `""`...) }returnAppendNull(, )}// AppendMarshalTextIndent is AppendMarshalText: the text has no indent.func ( *RuntimeContext, *Opcode, []byte, unsafe.Pointer) ([]byte, error) {returnAppendMarshalText(, , , )}func ( *RuntimeContext, []byte) []byte {returnappend(, "null"...)}func ( *RuntimeContext, []byte) []byte {returnappend(, ',')}func ( *RuntimeContext, []byte) []byte {returnappend(, ',', '\n')}func ( *RuntimeContext, *Opcode, []byte) []byte { = append(, '\n') = append(, .Prefix...) := .BaseIndent + .Indent - 1for := uint32(0); < ; ++ { = append(, .IndentStr...) }returnappend(, '}', ',', '\n')}func ( *RuntimeContext, []byte, uint32) []byte { = append(, .Prefix...) := .BaseIndent + for := uint32(0); < ; ++ { = append(, .IndentStr...) }return}
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.