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 (
	
	
	
	

	
	
	
	
	
	
	
	
	
	
	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 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.
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.
EmitASCII specifies whether to format strings and bytes as ASCII only as opposed to using UTF-8 encoding when possible.
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.
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.
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.
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
	}
	.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) ( pref.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 known fields.
	 := .Fields()
	 := .Len()
	for  := 0;  < ; {
		 := .Get()
		if  := .ContainingOneof();  != nil {
			 = .WhichOneof()
			 += .Fields().Len()
		} else {
			++
		}

		if  == nil || !.Has() {
			continue
		}

Use type name for group field name.
		if .Kind() == pref.GroupKind {
			 = .Message().Name()
		}
		 := .Get()
		if  := .marshalField(string(), , );  != nil {
			return 
		}
	}
Marshal extensions.
	if  := .marshalExtensions();  != nil {
		return 
	}
Marshal unknown fields.
	if .opts.EmitUnknown {
		.marshalUnknown(.GetUnknown())
	}

	return nil
}
marshalField marshals the given field with protoreflect.Value.
func ( encoder) ( string,  pref.Value,  pref.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.
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(string(.Bytes()))

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

	case pref.MessageKind, pref.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,  pref.List,  pref.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,  pref.Map,  pref.FieldDescriptor) error {
	var  error
	mapsort.Range(, .MapKey().Kind(), func( pref.MapKey,  pref.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 
}
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()
		}
		 = append(, {
			:   string(),
			: ,
			:  ,
		})
		return true
Sort extensions lexicographically.
	sort.Slice(, func(,  int) bool {
		return []. < [].
	})
Write out sorted list.
Extension field name is the proto field name enclosed in [].
		 := "[" + . + "]"
		if  := .marshalField(, ., .);  != nil {
			return 
		}
	}
	return nil
}
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.
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