// 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 (
	
	

	
	
	
	
	
	
	
	
	
	
	
)

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.
func ( proto.Message) string {
	return MarshalOptions{Multiline: true}.Format()
}

// 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.
type MarshalOptions struct {
	pragma.NoUnkeyedLiterals

	// 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.
	Multiline bool

	// 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.
	Indent string

	// 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.
	AllowPartial bool

	// UseProtoNames uses proto field name instead of lowerCamelCase name in JSON
	// field names.
	UseProtoNames bool

	// UseEnumNumbers emits enum values as numbers.
	UseEnumNumbers bool

	// 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                 ║
	//  ╚═══════╧════════════════════════════╝
	EmitUnpopulated bool

	// Resolver is used for looking up types when expanding google.protobuf.Any
	// messages. If nil, this defaults to using protoregistry.GlobalTypes.
	Resolver interface {
		protoregistry.ExtensionTypeResolver
		protoregistry.MessageTypeResolver
	}
}

// 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
}

// typeFieldDesc is a synthetic field descriptor used for the "@type" field.
var typeFieldDesc = func() protoreflect.FieldDescriptor {
	var  filedesc.Field
	.L0.FullName = "@type"
	.L0.Index = -1
	.L1.Cardinality = protoreflect.Optional
	.L1.Kind = protoreflect.StringKind
	return &
}()

// typeURLFieldRanger wraps a protoreflect.Message and modifies its Range method
// to additionally iterate over a synthetic field for the type URL.
type typeURLFieldRanger struct {
	order.FieldRanger
	typeURL string
}

func ( typeURLFieldRanger) ( func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {
	if !(typeFieldDesc, protoreflect.ValueOfString(.typeURL)) {
		return
	}
	.FieldRanger.Range()
}

// unpopulatedFieldRanger wraps a protoreflect.Message and modifies its Range
// method to additionally iterate over unpopulated fields.
type unpopulatedFieldRanger struct{ protoreflect.Message }

func ( unpopulatedFieldRanger) ( func(protoreflect.FieldDescriptor, protoreflect.Value) bool) {
	 := .Descriptor().Fields()
	for  := 0;  < .Len(); ++ {
		 := .Get()
		if .Has() || .ContainingOneof() != nil {
			continue // ignore populated fields and fields within a oneofs
		}

		 := .Get()
		 := .Syntax() == protoreflect.Proto2 && .Default().IsValid()
		 := .Cardinality() != protoreflect.Repeated && .Message() != nil
		if  ||  {
			 = protoreflect.Value{} // use invalid value to emit null
		}
		if !(, ) {
			return
		}
	}
	.Message.Range()
}

// marshalMessage marshals the fields in the given protoreflect.Message.
// If the typeURL is non-empty, then a synthetic "@type" field is injected
// containing the URL as the value.
func ( encoder) ( protoreflect.Message,  string) error {
	if !flags.ProtoLegacy && messageset.IsMessageSet(.Descriptor()) {
		return errors.New("no support for proto1 MessageSets")
	}

	if  := wellKnownTypeMarshaler(.Descriptor().FullName());  != nil {
		return (, )
	}

	.StartObject()
	defer .EndObject()

	var  order.FieldRanger = 
	if .opts.EmitUnpopulated {
		 = unpopulatedFieldRanger{}
	}
	if  != "" {
		 = typeURLFieldRanger{, }
	}

	var  error
	order.RangeFields(, order.IndexNameFieldOrder, func( protoreflect.FieldDescriptor,  protoreflect.Value) bool {
		 := .JSONName()
		if .opts.UseProtoNames {
			 = .TextName()
		}

		if  = .WriteName();  != nil {
			return false
		}
		if  = .marshalValue(, );  != nil {
			return false
		}
		return true
	})
	return 
}

// marshalValue marshals the given protoreflect.Value.
func ( encoder) ( protoreflect.Value,  protoreflect.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) ( protoreflect.Value,  protoreflect.FieldDescriptor) error {
	if !.IsValid() {
		.WriteNull()
		return nil
	}

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

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

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

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

	case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Uint64Kind,
		protoreflect.Sfixed64Kind, protoreflect.Fixed64Kind:
		// 64-bit integers are written out as JSON string.
		.WriteString(.String())

	case protoreflect.FloatKind:
		// Encoder.WriteFloat handles the special numbers NaN and infinites.
		.WriteFloat(.Float(), 32)

	case protoreflect.DoubleKind:
		// Encoder.WriteFloat handles the special numbers NaN and infinites.
		.WriteFloat(.Float(), 64)

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

	case protoreflect.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 protoreflect.MessageKind, protoreflect.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) ( protoreflect.List,  protoreflect.FieldDescriptor) error {
	.StartArray()
	defer .EndArray()

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

// marshalMap marshals given protoreflect.Map.
func ( encoder) ( protoreflect.Map,  protoreflect.FieldDescriptor) error {
	.StartObject()
	defer .EndObject()

	var  error
	order.RangeEntries(, order.GenericKeyOrder, func( protoreflect.MapKey,  protoreflect.Value) bool {
		if  = .WriteName(.String());  != nil {
			return false
		}
		if  = .marshalSingular(, .MapValue());  != nil {
			return false
		}
		return true
	})
	return 
}