Copyright 2019 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 protojson

import (
	
	
	

	
	
	
	
	
	
	
	pref 
	
)

const defaultIndent = "  "
Format formats the message as a multiline string. This function is only intended for human consumption and ignores errors. Do not depend on the output being stable. It may change over time across different versions of the program.
Marshal writes the given proto.Message in JSON format using default options. Do not depend on the output being stable. It may change over time across different versions of the program.
func ( proto.Message) ([]byte, error) {
	return MarshalOptions{}.Marshal()
}
MarshalOptions is a configurable JSON format marshaler.
Multiline specifies whether the marshaler should format the output in indented-form with every textual element on a new line. If Indent is an empty string, then an arbitrary indent is chosen.
Indent specifies the set of indentation characters to use in a multiline formatted output such that every entry is preceded by Indent and terminated by a newline. If non-empty, then Multiline is treated as true. Indent can only be composed of space or tab characters.
AllowPartial allows messages that have missing required fields to marshal without returning an error. If AllowPartial is false (the default), Marshal will return error if there are any missing required fields.
UseProtoNames uses proto field name instead of lowerCamelCase name in JSON field names.
UseEnumNumbers emits enum values as numbers.
EmitUnpopulated specifies whether to emit unpopulated fields. It does not emit unpopulated oneof fields or unpopulated extension fields. The JSON value emitted for unpopulated fields are as follows: ╔═══════╤════════════════════════════╗ ║ JSON │ Protobuf field ║ ╠═══════╪════════════════════════════╣ ║ false │ proto3 boolean fields ║ ║ 0 │ proto3 numeric fields ║ ║ "" │ proto3 string/bytes fields ║ ║ null │ proto2 scalar fields ║ ║ null │ message fields ║ ║ [] │ list fields ║ ║ {} │ map fields ║ ╚═══════╧════════════════════════════╝
Resolver is used for looking up types when expanding google.protobuf.Any messages. If nil, this defaults to using protoregistry.GlobalTypes.
Format formats the message as a string. This method is only intended for human consumption and ignores errors. Do not depend on the output being stable. It may change over time across different versions of the program.
func ( MarshalOptions) ( proto.Message) string {
	if  == nil || !.ProtoReflect().IsValid() {
		return "<nil>" // invalid syntax, but okay since this is for debugging
	}
	.AllowPartial = true
	,  := .Marshal()
	return string()
}
Marshal marshals the given proto.Message in the JSON format using options in MarshalOptions. Do not depend on the output being stable. It may change over time across different versions of the program.
func ( MarshalOptions) ( proto.Message) ([]byte, error) {
	return .marshal()
}
marshal is a centralized function that all marshal operations go through. For profiling purposes, avoid changing the name of this function or introducing other code paths for marshal that do not go through this.
func ( MarshalOptions) ( proto.Message) ([]byte, error) {
	if .Multiline && .Indent == "" {
		.Indent = defaultIndent
	}
	if .Resolver == nil {
		.Resolver = protoregistry.GlobalTypes
	}

	,  := json.NewEncoder(.Indent)
	if  != nil {
		return nil, 
	}
Treat nil message interface as an empty message, in which case the output in an empty JSON object.
	if  == nil {
		return []byte("{}"), nil
	}

	 := encoder{, }
	if  := .marshalMessage(.ProtoReflect());  != nil {
		return nil, 
	}
	if .AllowPartial {
		return .Bytes(), nil
	}
	return .Bytes(), proto.CheckInitialized()
}

type encoder struct {
	*json.Encoder
	opts MarshalOptions
}
marshalMessage marshals the given protoreflect.Message.
func ( encoder) ( pref.Message) error {
	if  := wellKnownTypeMarshaler(.Descriptor().FullName());  != nil {
		return (, )
	}

	.StartObject()
	defer .EndObject()
	if  := .marshalFields();  != nil {
		return 
	}

	return nil
}
marshalFields marshals the fields in the given protoreflect.Message.
func ( encoder) ( pref.Message) error {
	 := .Descriptor()
	if !flags.ProtoLegacy && messageset.IsMessageSet() {
		return errors.New("no support for proto1 MessageSets")
	}
Marshal out known fields.
	 := .Fields()
	for  := 0;  < .Len(); {
		 := .Get()
		if  := .ContainingOneof();  != nil {
			 = .WhichOneof()
			 += .Fields().Len()
			if  == nil {
				continue // unpopulated oneofs are not affected by EmitUnpopulated
			}
		} else {
			++
		}

		 := .Get()
		if !.Has() {
			if !.opts.EmitUnpopulated {
				continue
			}
			 := .Syntax() == pref.Proto2 && .Default().IsValid()
			 := .Cardinality() != pref.Repeated && .Message() != nil
Use invalid value to emit null.
				 = pref.Value{}
			}
		}

		 := .JSONName()
		if .opts.UseProtoNames {
Use type name for group field name.
			if .Kind() == pref.GroupKind {
				 = string(.Message().Name())
			}
		}
		if  := .WriteName();  != nil {
			return 
		}
		if  := .marshalValue(, );  != nil {
			return 
		}
	}
Marshal out extensions.
	if  := .marshalExtensions();  != nil {
		return 
	}
	return nil
}
marshalValue marshals the given protoreflect.Value.
func ( encoder) ( pref.Value,  pref.FieldDescriptor) error {
	switch {
	case .IsList():
		return .marshalList(.List(), )
	case .IsMap():
		return .marshalMap(.Map(), )
	default:
		return .marshalSingular(, )
	}
}
marshalSingular marshals the given non-repeated field value. This includes all scalar types, enums, messages, and groups.
func ( encoder) ( pref.Value,  pref.FieldDescriptor) error {
	if !.IsValid() {
		.WriteNull()
		return nil
	}

	switch  := .Kind();  {
	case pref.BoolKind:
		.WriteBool(.Bool())

	case pref.StringKind:
		if .WriteString(.String()) != nil {
			return errors.InvalidUTF8(string(.FullName()))
		}

	case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
		.WriteInt(.Int())

	case pref.Uint32Kind, pref.Fixed32Kind:
		.WriteUint(.Uint())

	case pref.Int64Kind, pref.Sint64Kind, pref.Uint64Kind,
64-bit integers are written out as JSON string.
		.WriteString(.String())

Encoder.WriteFloat handles the special numbers NaN and infinites.
		.WriteFloat(.Float(), 32)

Encoder.WriteFloat handles the special numbers NaN and infinites.
		.WriteFloat(.Float(), 64)

	case pref.BytesKind:
		.WriteString(base64.StdEncoding.EncodeToString(.Bytes()))

	case pref.EnumKind:
		if .Enum().FullName() == genid.NullValue_enum_fullname {
			.WriteNull()
		} else {
			 := .Enum().Values().ByNumber(.Enum())
			if .opts.UseEnumNumbers ||  == nil {
				.WriteInt(int64(.Enum()))
			} else {
				.WriteString(string(.Name()))
			}
		}

	case pref.MessageKind, pref.GroupKind:
		if  := .marshalMessage(.Message());  != nil {
			return 
		}

	default:
		panic(fmt.Sprintf("%v has unknown kind: %v", .FullName(), ))
	}
	return nil
}
marshalList marshals the given protoreflect.List.
func ( encoder) ( pref.List,  pref.FieldDescriptor) error {
	.StartArray()
	defer .EndArray()

	for  := 0;  < .Len(); ++ {
		 := .Get()
		if  := .marshalSingular(, );  != nil {
			return 
		}
	}
	return nil
}

type mapEntry struct {
	key   pref.MapKey
	value pref.Value
}
marshalMap marshals given protoreflect.Map.
Get a sorted list based on keyType first.
	 := make([]mapEntry, 0, .Len())
	.Range(func( pref.MapKey,  pref.Value) bool {
		 = append(, mapEntry{key: , value: })
		return true
	})
	sortMap(.MapKey().Kind(), )
Write out sorted list.
	for ,  := range  {
		if  := .WriteName(.key.String());  != nil {
			return 
		}
		if  := .marshalSingular(.value, .MapValue());  != nil {
			return 
		}
	}
	return nil
}
sortMap orders list based on value of key field for deterministic ordering.
func ( pref.Kind,  []mapEntry) {
	sort.Slice(, func(,  int) bool {
		switch  {
		case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind,
			pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
			return [].key.Int() < [].key.Int()

		case pref.Uint32Kind, pref.Fixed32Kind,
			pref.Uint64Kind, pref.Fixed64Kind:
			return [].key.Uint() < [].key.Uint()
		}
		return [].key.String() < [].key.String()
	})
}
marshalExtensions marshals extension fields.
func ( encoder) ( pref.Message) error {
	type  struct {
		   string
		 pref.Value
		  pref.FieldDescriptor
	}
Get a sorted list based on field key first.
	var  []
	.Range(func( pref.FieldDescriptor,  pref.Value) bool {
		if !.IsExtension() {
			return true
		}
For MessageSet extensions, the name used is the parent message.
		 := .FullName()
		if messageset.IsMessageSetExtension() {
			 = .Parent()
		}
Use [name] format for JSON field name.
		 = append(, {
			:   string(),
			: ,
			:  ,
		})
		return true
	})
Sort extensions lexicographically.
	sort.Slice(, func(,  int) bool {
		return []. < [].
	})
Write out sorted list.
JSON field name is the proto field name enclosed in [], similar to textproto. This is consistent with Go v1 lib. C++ lib v3.7.0 does not marshal out extension fields.
		if  := .WriteName("[" + . + "]");  != nil {
			return 
		}
		if  := .marshalValue(., .);  != nil {
			return 
		}
	}
	return nil