// Copyright 2018 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 prototext

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 textproto 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 text 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

	// EmitASCII specifies whether to format strings and bytes as ASCII only
	// as opposed to using UTF-8 encoding when possible.
	EmitASCII bool

	// allowInvalidUTF8 specifies whether to permit the encoding of strings
	// with invalid UTF-8. This is unexported as it is intended to only
	// be specified by the Format method.
	allowInvalidUTF8 bool

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

	// EmitUnknown specifies whether to emit unknown fields in the output.
	// If specified, the unmarshaler may be unable to parse the output.
	// The default is to exclude unknown fields.
	EmitUnknown 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
	}
	.allowInvalidUTF8 = true
	.AllowPartial = true
	.EmitUnknown = true
	,  := .Marshal()
	return string()
}

// Marshal writes the given proto.Message in textproto format using options in
// MarshalOptions object. 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) {
	var  = [2]byte{'{', '}'}

	if .Multiline && .Indent == "" {
		.Indent = defaultIndent
	}
	if .Resolver == nil {
		.Resolver = protoregistry.GlobalTypes
	}

	,  := text.NewEncoder(.Indent, , .EmitASCII)
	if  != nil {
		return nil, 
	}

	// Treat nil message interface as an empty message,
	// in which case there is nothing to output.
	if  == nil {
		return []byte{}, nil
	}

	 := encoder{, }
	 = .marshalMessage(.ProtoReflect(), false)
	if  != nil {
		return nil, 
	}
	 := .Bytes()
	if len(.Indent) > 0 && len() > 0 {
		 = append(, '\n')
	}
	if .AllowPartial {
		return , nil
	}
	return , proto.CheckInitialized()
}

type encoder struct {
	*text.Encoder
	opts MarshalOptions
}

// marshalMessage marshals the given protoreflect.Message.
func ( encoder) ( protoreflect.Message,  bool) error {
	 := .Descriptor()
	if !flags.ProtoLegacy && messageset.IsMessageSet() {
		return errors.New("no support for proto1 MessageSets")
	}

	if  {
		.StartMessage()
		defer .EndMessage()
	}

	// Handle Any expansion.
	if .FullName() == genid.Any_message_fullname {
		if .marshalAny() {
			return nil
		}
		// If unable to expand, continue on to marshal Any as a regular message.
	}

	// Marshal fields.
	var  error
	order.RangeFields(, order.IndexNameFieldOrder, func( protoreflect.FieldDescriptor,  protoreflect.Value) bool {
		if  = .marshalField(.TextName(), , );  != nil {
			return false
		}
		return true
	})
	if  != nil {
		return 
	}

	// Marshal unknown fields.
	if .opts.EmitUnknown {
		.marshalUnknown(.GetUnknown())
	}

	return nil
}

// marshalField marshals the given field with protoreflect.Value.
func ( encoder) ( string,  protoreflect.Value,  protoreflect.FieldDescriptor) error {
	switch {
	case .IsList():
		return .marshalList(, .List(), )
	case .IsMap():
		return .marshalMap(, .Map(), )
	default:
		.WriteName()
		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 {
	 := .Kind()
	switch  {
	case protoreflect.BoolKind:
		.WriteBool(.Bool())

	case protoreflect.StringKind:
		 := .String()
		if !.opts.allowInvalidUTF8 && strs.EnforceUTF8() && !utf8.ValidString() {
			return errors.InvalidUTF8(string(.FullName()))
		}
		.WriteString()

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

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

	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(string(.Bytes()))

	case protoreflect.EnumKind:
		 := .Enum()
		if  := .Enum().Values().ByNumber();  != nil {
			.WriteLiteral(string(.Name()))
		} else {
			// Use numeric value if there is no enum description.
			.WriteInt(int64())
		}

	case protoreflect.MessageKind, protoreflect.GroupKind:
		return .marshalMessage(.Message(), true)

	default:
		panic(fmt.Sprintf("%v has unknown kind: %v", .FullName(), ))
	}
	return nil
}

// marshalList marshals the given protoreflect.List as multiple name-value fields.
func ( encoder) ( string,  protoreflect.List,  protoreflect.FieldDescriptor) error {
	 := .Len()
	for  := 0;  < ; ++ {
		.WriteName()
		if  := .marshalSingular(.Get(), );  != nil {
			return 
		}
	}
	return nil
}

// marshalMap marshals the given protoreflect.Map as multiple name-value fields.
func ( encoder) ( string,  protoreflect.Map,  protoreflect.FieldDescriptor) error {
	var  error
	order.RangeEntries(, order.GenericKeyOrder, func( protoreflect.MapKey,  protoreflect.Value) bool {
		.WriteName()
		.StartMessage()
		defer .EndMessage()

		.WriteName(string(genid.MapEntry_Key_field_name))
		 = .marshalSingular(.Value(), .MapKey())
		if  != nil {
			return false
		}

		.WriteName(string(genid.MapEntry_Value_field_name))
		 = .marshalSingular(, .MapValue())
		if  != nil {
			return false
		}
		return true
	})
	return 
}

// marshalUnknown parses the given []byte and marshals fields out.
// This function assumes proper encoding in the given []byte.
func ( encoder) ( []byte) {
	const  = 10
	const  = 16
	for len() > 0 {
		, ,  := protowire.ConsumeTag()
		 = [:]
		.WriteName(strconv.FormatInt(int64(), ))

		switch  {
		case protowire.VarintType:
			var  uint64
			,  = protowire.ConsumeVarint()
			.WriteUint()
		case protowire.Fixed32Type:
			var  uint32
			,  = protowire.ConsumeFixed32()
			.WriteLiteral("0x" + strconv.FormatUint(uint64(), ))
		case protowire.Fixed64Type:
			var  uint64
			,  = protowire.ConsumeFixed64()
			.WriteLiteral("0x" + strconv.FormatUint(, ))
		case protowire.BytesType:
			var  []byte
			,  = protowire.ConsumeBytes()
			.WriteString(string())
		case protowire.StartGroupType:
			.StartMessage()
			var  []byte
			,  = protowire.ConsumeGroup(, )
			.()
			.EndMessage()
		default:
			panic(fmt.Sprintf("prototext: error parsing unknown field wire type: %v", ))
		}

		 = [:]
	}
}

// marshalAny marshals the given google.protobuf.Any message in expanded form.
// It returns true if it was able to marshal, else false.
func ( encoder) ( protoreflect.Message) bool {
	// Construct the embedded message.
	 := .Descriptor().Fields()
	 := .ByNumber(genid.Any_TypeUrl_field_number)
	 := .Get().String()
	,  := .opts.Resolver.FindMessageByURL()
	if  != nil {
		return false
	}
	 := .New().Interface()

	// Unmarshal bytes into embedded message.
	 := .ByNumber(genid.Any_Value_field_number)
	 := .Get()
	 = proto.UnmarshalOptions{
		AllowPartial: true,
		Resolver:     .opts.Resolver,
	}.Unmarshal(.Bytes(), )
	if  != nil {
		return false
	}

	// Get current encoder position. If marshaling fails, reset encoder output
	// back to this position.
	 := .Snapshot()

	// Field name is the proto field name enclosed in [].
	.WriteName("[" +  + "]")
	 = .marshalMessage(.ProtoReflect(), true)
	if  != nil {
		.Reset()
		return false
	}
	return true
}