Copyright 2020 The Go Authors. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.

package codec

import (
	
	
	
	
)
An Encoder encodes Go values into a sequence of bytes. To use an Encoder: - Create one with NewEncoder. - Call the Encode method one or more times. - Retrieve the resulting bytes by calling Bytes.
type Encoder struct {
	buf      []byte
	typeNums map[reflect.Type]int
	seen     map[interface{}]uint64 // for references; see StartStruct
}
NewEncoder returns an Encoder.
func () *Encoder {
	return &Encoder{
		typeNums: map[reflect.Type]int{},
		seen:     map[interface{}]uint64{},
	}
}
Encode encodes x.
func ( *Encoder) ( interface{}) ( error) {
	defer handlePanic(&)
	.EncodeAny()
	return nil
}

func ( *error) {
	 := recover()
No panic; do nothing.
		return
If the panic is not from this package, re-panic.
	,  := .(codecError)
	if ! {
		panic()
Otherwise, set errp.
	* = .err
}
codecError wraps errors from this package so handlePanic can distinguish them.
type codecError struct {
	err error
}

func ( error) {
	panic(codecError{})
}

func ( string,  ...interface{}) {
	fail(fmt.Errorf(, ...))
}
Bytes returns the encoded byte slice.
func ( *Encoder) () []byte {
	 := .buf                 // remember the data
	.buf = nil                   // start with a fresh buffer
	.encodeInitial()             // encode metadata
	return append(.buf, ...) // concatenate metadata and data
}
A Decoder decodes a Go value encoded by an Encoder. To use a Decoder: - Pass NewDecoder the return value of Encoder.Bytes. - Call the Decode method once for each call to Encoder.Encode.
type Decoder struct {
	buf       []byte
	i         int
	typeInfos []*typeInfo
	refs      []interface{} // list of struct pointers, in the order seen
}
NewDecoder returns a Decoder for the given bytes.
func ( []byte) *Decoder {
	return &Decoder{buf: , i: 0}
}
Decode decodes a value encoded with Encoder.Encode.
func ( *Decoder) () ( interface{},  error) {
	defer handlePanic(&)
	if .typeInfos == nil {
		.decodeInitial()
	}
	return .DecodeAny(), nil
}

func ( byte) {
	failf("bad code: %d", )
}
////////////// Reading From and Writing To the Buffer

func ( *Encoder) ( byte) {
	.buf = append(.buf, )
}

func ( *Decoder) () byte {
	 := .curByte()
	.i++
	return 
}
curByte returns the next byte to be read without actually consuming it.
func ( *Decoder) () byte {
	return .buf[.i]
}

func ( *Encoder) ( []byte) {
	.buf = append(.buf, ...)
}
readBytes reads and returns the given number of bytes. It fails if there are not enough bytes in the input.
func ( *Decoder) ( int) []byte {
	.i += 
	return .buf[.i- : .i]
}

func ( *Encoder) ( string) {
	.buf = append(.buf, ...)
}

func ( *Decoder) ( int) string {
	return string(.readBytes())
}

func ( *Encoder) ( uint32) {
	var  [4]byte
	binary.LittleEndian.PutUint32([:], )
	.writeBytes([:])
}

func ( *Decoder) () uint32 {
	return binary.LittleEndian.Uint32(.readBytes(4))
}

func ( *Encoder) ( uint64) {
	var  [8]byte
	binary.LittleEndian.PutUint64([:], )
	.writeBytes([:])
}

func ( *Decoder) () uint64 {
	return binary.LittleEndian.Uint64(.readBytes(8))
}
////////////// Encoding Scheme
Byte codes that begin each encoded value. See the package doc for their descriptions.
const (
reserve a few values for future use
	reserved1
	reserved2
	reserved3
	reserved4
	reserved5
	reserved6
	reserved7
	nBytesCode  // uint n follows, then n bytes
	nValuesCode // uint n follows, then n values
	refCode     // uint n follows, referring to a previous value
	startCode   // start of a value of indeterminate length
Bytes less than endCode represent themselves.
)
EncodeUint encodes a uint64.
func ( *Encoder) ( uint64) {
	switch {
u fits into the initial byte.
		.writeByte(byte())
Encode as a sequence of 4 bytes, the little-endian representation of a uint32.
Encode as a sequence of 8 bytes, the little-endian representation of a uint64.
DecodeUint decodes a uint64.
func ( *Decoder) () uint64 {
	 := .readByte()
	switch {
	case  < endCode:
		return uint64()
	case  == nBytesCode:
		switch  := .readByte();  {
		case 4:
			return uint64(.readUint32())
		case 8:
			return .readUint64()
		default:
			failf("DecodeUint: bad length %d", )
		}
	default:
		badcode()
	}
	return 0
}
EncodeInt encodes a signed integer.
Encode small negative as well as small positive integers efficiently. Algorithm from gob; see "Encoding Details" at https://pkg.go.dev/encoding/gob.
	var  uint64
	if  < 0 {
		 = (^uint64() << 1) | 1 // complement i, bit 0 is 1
	} else {
		 = (uint64() << 1) // do not complement i, bit 0 is 0
	}
	.EncodeUint()
}
DecodeInt decodes a signed integer.
func ( *Decoder) () int64 {
	 := .DecodeUint()
	if &1 == 1 {
		return int64(^( >> 1))
	}
	return int64( >> 1)
}
encodeLen encodes the length of a byte sequence.
decodeLen decodes the length of a byte sequence.
func ( *Decoder) () int {
	if  := .readByte();  != nBytesCode {
		badcode()
	}
	return int(.DecodeUint())
}
EncodeBytes encodes a byte slice.
func ( *Encoder) ( []byte) {
	.encodeLen(len())
	.writeBytes()
}
DecodeBytes decodes a byte slice. It does no copying.
func ( *Decoder) () []byte {
	return .readBytes(.decodeLen())
}
EncodeString encodes a string.
func ( *Encoder) ( string) {
	.encodeLen(len())
	.writeString()
}
DecodeString decodes a string.
func ( *Decoder) () string {
	return .readString(.decodeLen())
}
EncodeBool encodes a bool.
func ( *Encoder) ( bool) {
	if  {
		.writeByte(1)
	} else {
		.writeByte(0)
	}
}
DecodeBool decodes a bool.
func ( *Decoder) () bool {
	 := .readByte()
	switch  {
	case 0:
		return false
	case 1:
		return true
	default:
		failf("bad bool: %d", )
		return false
	}
}
EncodeFloat encodes a float64.
DecodeFloat decodes a float64.
StartList should be called before encoding any sequence of variable-length values.
func ( *Encoder) ( int) {
	.writeByte(nValuesCode)
	.EncodeUint(uint64())
}
StartList should be called before decoding any sequence of variable-length values. It returns -1 if the encoded list was nil. Otherwise, it returns the length of the sequence.
func ( *Decoder) () int {
	switch  := .readByte();  {
	case nilCode:
		return -1
	case nValuesCode:
		return int(.DecodeUint())
	default:
		badcode()
		return 0
	}
}
////////////// Struct Support
StartStruct should be called before encoding a struct pointer. The isNil argument says whether the pointer is nil. The p argument is the struct pointer. If StartStruct returns false, encoding should not proceed.
func ( *Encoder) ( bool,  interface{}) bool {
	if  {
		.EncodeNil()
		return false
	}
If we have already seen this struct pointer, encode a reference to it.
		.writeByte(refCode)
		.EncodeUint()
		return false // Caller should not encode the struct.
Note that we have seen this pointer, and assign it its position in the encoding.
	.seen[] = uint64(len(.seen))
	.writeByte(startCode)
	return true
}
StartStruct should be called before decoding a struct pointer. If it returns false, decoding should not proceed. If it returns true and the second return value is non-nil, it is a reference to a previous value and should be used instead of proceeding with decoding.
func ( *Decoder) () (bool, interface{}) {
	 := .readByte()
	switch  {
	case nilCode: // do not set the pointer
		return false, nil
	case refCode:
		 := .DecodeUint()
		return true, .refs[]
	case startCode:
		return true, nil
	default:
		badcode()
		return false, nil // unreached, needed for compiler
	}
}
StoreRef should be called by a struct decoder immediately after it allocates a struct pointer.
func ( *Decoder) ( interface{}) {
	.refs = append(.refs, )
}
EndStruct should be called after encoding a struct.
func ( *Encoder) () {
	.writeByte(endCode)
}
NextStructField should be called by a struct decoder in a loop. It returns the field number of the next encoded field, or -1 if there are no more fields.
func ( *Decoder) () int {
	if .curByte() == endCode {
		.readByte() // consume the end byte
		return -1
	}
	return int(.DecodeUint())
}
UnknownField should be called by a struct decoder when it sees a field number that it doesn't know.
func ( *Decoder) ( string,  int) {
	.skip()
}
skip reads past a value in the input.
func ( *Decoder) () {
	 := .readByte()
Small integers represent themselves in a single byte.
		return
	}
	switch  {
Nothing follows.
A uint n and n bytes follow. It is efficient to call readBytes here because it does no allocation.
A uint n and n values follow.
		 := int(.DecodeUint())
		for  := 0;  < ; ++ {
			.()
		}
A uint follows.
Skip until we see endCode.
		for .curByte() != endCode {
			.()
		}
		.readByte() // consume the endCode byte
	default:
		badcode()
	}
}
////////////// Encoding Arbitrary Values
EncodeAny encodes a Go type. The type must have been registered with Register.
Encode a nil interface value with a zero.
	if  == nil {
		.writeByte(0)
		return
Find the typeInfo for the type, which has the encoder.
	 := reflect.TypeOf()
	 := typeInfosByType[]
	if  == nil {
		failf("unregistered type %s", )
Assign a number to the type if we haven't already.
	,  := .typeNums[]
	if ! {
		 = len(.typeNums)
		.typeNums[] = 
Encode a pair (2-element list) of the type number and the encoded value.
	.StartList(2)
	.EncodeUint(uint64())
	.encode(, )
}
DecodeAny decodes a value encoded by EncodeAny.
If we're looking at a zero, this is a nil interface.
	if .curByte() == 0 {
		.readByte() // consume the byte
		return nil
Otherwise, we should have a two-item list: type number and value.
	 := .StartList()
	if  != 2 {
		failf("DecodeAny: bad list length %d", )
	}
	 := .DecodeUint()
	if  >= uint64(len(.typeInfos)) {
		failf("type number %d out of range", )
	}
	 := .typeInfos[]
	return .decode()
}
encodeInitial encodes metadata that appears at the start of the encoded byte slice.
Encode the list of type names we saw, in the order we assigned numbers to them.
	 := make([]string, len(.typeNums))
	for ,  := range .typeNums {
		[] = typeName()
	}
	.StartList(len())
	for ,  := range  {
		.EncodeString()
	}
}
decodeInitial decodes metadata that appears at the start of the encoded byte slice.
Decode the list of type names. The number of a type is its position in the list.
	 := .StartList()
	.typeInfos = make([]*typeInfo, )
	for  := 0;  < ; ++ {
		 := .DecodeString()
		 := typeInfosByName[]
		if  == nil {
			failf("unregistered type: %s", )
		}
		.typeInfos[] = 
	}
}
////////////// Type Registry
All types subject to encoding must be registered, even builtin types.
A typeInfo describes how to encode and decode a type.
type typeInfo struct {
	name   string // e.g. "go/ast.File"
	encode encodeFunc
	decode decodeFunc
}

type (
	encodeFunc func(*Encoder, interface{})
	decodeFunc func(*Decoder) interface{}
)

var (
	typeInfosByName = map[string]*typeInfo{}
	typeInfosByType = map[reflect.Type]*typeInfo{}
)
Register records the type of x for use by Encoders and Decoders.
func ( interface{},  encodeFunc,  decodeFunc) {
	 := reflect.TypeOf()
	 := typeName()
	if ,  := typeInfosByName[];  {
		panic(fmt.Sprintf("codec.Register: duplicate type %s (typeName=%q)", , ))
	}
	 := &typeInfo{
		name:   ,
		encode: ,
		decode: ,
	}
	typeInfosByName[.name] = 
	typeInfosByType[] = 
}
typeName returns the full, qualified name for a type.
func ( reflect.Type) string {
	if .PkgPath() == "" {
		return .String()
	}
	return .PkgPath() + "." + .Name()
}

var builtinTypes []reflect.Type

func () {
	Register(int64(0),
		func( *Encoder,  interface{}) { .EncodeInt(.(int64)) },
		func( *Decoder) interface{} { return .DecodeInt() })
	Register(uint64(0),
		func( *Encoder,  interface{}) { .EncodeUint(.(uint64)) },
		func( *Decoder) interface{} { return .DecodeUint() })
	Register(int(0),
		func( *Encoder,  interface{}) { .EncodeInt(int64(.(int))) },
		func( *Decoder) interface{} { return int(.DecodeInt()) })
	Register(float64(0),
		func( *Encoder,  interface{}) { .EncodeFloat(.(float64)) },
		func( *Decoder) interface{} { return .DecodeFloat() })
	Register(false,
		func( *Encoder,  interface{}) { .EncodeBool(.(bool)) },
		func( *Decoder) interface{} { return .DecodeBool() })
	Register("",
		func( *Encoder,  interface{}) { .EncodeString(.(string)) },
		func( *Decoder) interface{} { return .DecodeString() })
	Register([]byte(nil),
		func( *Encoder,  interface{}) { .EncodeBytes(.([]byte)) },
		func( *Decoder) interface{} { return .DecodeBytes() })

	for  := range typeInfosByType {
		builtinTypes = append(builtinTypes, )
	}