Lines Matching refs:P

341 		g.P("// New marshals src into a new Any instance.")
342 g.P("func New(src ", protoPackage.Ident("Message"), ") (*Any, error) {")
343 g.P(" dst := new(Any)")
344 g.P(" if err := dst.MarshalFrom(src); err != nil {")
345 g.P(" return nil, err")
346 g.P(" }")
347 g.P(" return dst, nil")
348 g.P("}")
349 g.P()
351 g.P("// MarshalFrom marshals src into dst as the underlying message")
352 g.P("// using the provided marshal options.")
353 g.P("//")
354 g.P("// If no options are specified, call dst.MarshalFrom instead.")
355 …g.P("func MarshalFrom(dst *Any, src ", protoPackage.Ident("Message"), ", opts ", protoPackage.Iden…
356 g.P(" const urlPrefix = \"type.googleapis.com/\"")
357 g.P(" if src == nil {")
358 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid nil source message\")")
359 g.P(" }")
360 g.P(" b, err := opts.Marshal(src)")
361 g.P(" if err != nil {")
362 g.P(" return err")
363 g.P(" }")
364 g.P(" dst.TypeUrl = urlPrefix + string(src.ProtoReflect().Descriptor().FullName())")
365 g.P(" dst.Value = b")
366 g.P(" return nil")
367 g.P("}")
368 g.P()
370 g.P("// UnmarshalTo unmarshals the underlying message from src into dst")
371 g.P("// using the provided unmarshal options.")
372 g.P("// It reports an error if dst is not of the right message type.")
373 g.P("//")
374 g.P("// If no options are specified, call src.UnmarshalTo instead.")
375 …g.P("func UnmarshalTo(src *Any, dst ", protoPackage.Ident("Message"), ", opts ", protoPackage.Iden…
376 g.P(" if src == nil {")
377 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid nil source message\")")
378 g.P(" }")
379 g.P(" if !src.MessageIs(dst) {")
380 g.P(" got := dst.ProtoReflect().Descriptor().FullName()")
381 g.P(" want := src.MessageName()")
382 …g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"mismatched message type: got %q, want %…
383 g.P(" }")
384 g.P(" return opts.Unmarshal(src.GetValue(), dst)")
385 g.P("}")
386 g.P()
388 g.P("// UnmarshalNew unmarshals the underlying message from src into dst,")
389 g.P("// which is newly created message using a type resolved from the type URL.")
390 g.P("// The message type is resolved according to opt.Resolver,")
391 g.P("// which should implement protoregistry.MessageTypeResolver.")
392 g.P("// It reports an error if the underlying message type could not be resolved.")
393 g.P("//")
394 g.P("// If no options are specified, call src.UnmarshalNew instead.")
395 …g.P("func UnmarshalNew(src *Any, opts ", protoPackage.Ident("UnmarshalOptions"), ") (dst ", protoP…
396 g.P(" if src.GetTypeUrl() == \"\" {")
397 g.P(" return nil, ", protoimplPackage.Ident("X"), ".NewError(\"invalid empty type URL\")")
398 g.P(" }")
399 g.P(" if opts.Resolver == nil {")
400 g.P(" opts.Resolver = ", protoregistryPackage.Ident("GlobalTypes"))
401 g.P(" }")
402 g.P(" r, ok := opts.Resolver.(", protoregistryPackage.Ident("MessageTypeResolver"), ")")
403 g.P(" if !ok {")
404 g.P(" return nil, ", protoregistryPackage.Ident("NotFound"))
405 g.P(" }")
406 g.P(" mt, err := r.FindMessageByURL(src.GetTypeUrl())")
407 g.P(" if err != nil {")
408 g.P(" if err == ", protoregistryPackage.Ident("NotFound"), " {")
409 g.P(" return nil, err")
410 g.P(" }")
411 …g.P(" return nil, ", protoimplPackage.Ident("X"), ".NewError(\"could not resolve %q: %v\", src.Ge…
412 g.P(" }")
413 g.P(" dst = mt.New().Interface()")
414 g.P(" return dst, opts.Unmarshal(src.GetValue(), dst)")
415 g.P("}")
416 g.P()
418 g.P("// MessageIs reports whether the underlying message is of the same type as m.")
419 g.P("func (x *Any) MessageIs(m ", protoPackage.Ident("Message"), ") bool {")
420 g.P(" if m == nil {")
421 g.P(" return false")
422 g.P(" }")
423 g.P(" url := x.GetTypeUrl()")
424 g.P(" name := string(m.ProtoReflect().Descriptor().FullName())")
425 g.P(" if !", stringsPackage.Ident("HasSuffix"), "(url, name) {")
426 g.P(" return false")
427 g.P(" }")
428 g.P(" return len(url) == len(name) || url[len(url)-len(name)-1] == '/'")
429 g.P("}")
430 g.P()
432 g.P("// MessageName reports the full name of the underlying message,")
433 g.P("// returning an empty string if invalid.")
434 g.P("func (x *Any) MessageName() ", protoreflectPackage.Ident("FullName"), " {")
435 g.P(" url := x.GetTypeUrl()")
436 g.P(" name := ", protoreflectPackage.Ident("FullName"), "(url)")
437 g.P(" if i := ", stringsPackage.Ident("LastIndexByte"), "(url, '/'); i >= 0 {")
438 g.P(" name = name[i+len(\"/\"):]")
439 g.P(" }")
440 g.P(" if !name.IsValid() {")
441 g.P(" return \"\"")
442 g.P(" }")
443 g.P(" return name")
444 g.P("}")
445 g.P()
447 g.P("// MarshalFrom marshals m into x as the underlying message.")
448 g.P("func (x *Any) MarshalFrom(m ", protoPackage.Ident("Message"), ") error {")
449 g.P(" return MarshalFrom(x, m, ", protoPackage.Ident("MarshalOptions"), "{})")
450 g.P("}")
451 g.P()
453 g.P("// UnmarshalTo unmarshals the contents of the underlying message of x into m.")
454 g.P("// It resets m before performing the unmarshal operation.")
455 g.P("// It reports an error if m is not of the right message type.")
456 g.P("func (x *Any) UnmarshalTo(m ", protoPackage.Ident("Message"), ") error {")
457 g.P(" return UnmarshalTo(x, m, ", protoPackage.Ident("UnmarshalOptions"), "{})")
458 g.P("}")
459 g.P()
461 g.P("// UnmarshalNew unmarshals the contents of the underlying message of x into")
462 g.P("// a newly allocated message of the specified type.")
463 g.P("// It reports an error if the underlying message type could not be resolved.")
464 g.P("func (x *Any) UnmarshalNew() (", protoPackage.Ident("Message"), ", error) {")
465 g.P(" return UnmarshalNew(x, ", protoPackage.Ident("UnmarshalOptions"), "{})")
466 g.P("}")
467 g.P()
470 g.P("// Now constructs a new Timestamp from the current time.")
471 g.P("func Now() *Timestamp {")
472 g.P(" return New(", timePackage.Ident("Now"), "())")
473 g.P("}")
474 g.P()
476 g.P("// New constructs a new Timestamp from the provided time.Time.")
477 g.P("func New(t ", timePackage.Ident("Time"), ") *Timestamp {")
478 g.P(" return &Timestamp{Seconds: int64(t.Unix()), Nanos: int32(t.Nanosecond())}")
479 g.P("}")
480 g.P()
482 g.P("// AsTime converts x to a time.Time.")
483 g.P("func (x *Timestamp) AsTime() ", timePackage.Ident("Time"), " {")
484 g.P(" return ", timePackage.Ident("Unix"), "(int64(x.GetSeconds()), int64(x.GetNanos())).UTC()")
485 g.P("}")
486 g.P()
488 g.P("// IsValid reports whether the timestamp is valid.")
489 g.P("// It is equivalent to CheckValid == nil.")
490 g.P("func (x *Timestamp) IsValid() bool {")
491 g.P(" return x.check() == 0")
492 g.P("}")
493 g.P()
495 g.P("// CheckValid returns an error if the timestamp is invalid.")
496 g.P("// In particular, it checks whether the value represents a date that is")
497 g.P("// in the range of 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive.")
498 g.P("// An error is reported for a nil Timestamp.")
499 g.P("func (x *Timestamp) CheckValid() error {")
500 g.P(" switch x.check() {")
501 g.P(" case invalidNil:")
502 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid nil Timestamp\")")
503 g.P(" case invalidUnderflow:")
504 …g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"timestamp (%v) before 0001-01-01\", x)")
505 g.P(" case invalidOverflow:")
506 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"timestamp (%v) after 9999-12-31\", x)")
507 g.P(" case invalidNanos:")
508 …g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"timestamp (%v) has out-of-range nanos\"…
509 g.P(" default:")
510 g.P(" return nil")
511 g.P(" }")
512 g.P("}")
513 g.P()
515 g.P("const (")
516 g.P(" _ = iota")
517 g.P(" invalidNil")
518 g.P(" invalidUnderflow")
519 g.P(" invalidOverflow")
520 g.P(" invalidNanos")
521 g.P(")")
522 g.P()
524 g.P("func (x *Timestamp) check() uint {")
525 …g.P(" const minTimestamp = -62135596800 // Seconds between 1970-01-01T00:00:00Z and 0001-01-01T00…
526 …g.P(" const maxTimestamp = +253402300799 // Seconds between 1970-01-01T00:00:00Z and 9999-12-31T23…
527 g.P(" secs := x.GetSeconds()")
528 g.P(" nanos := x.GetNanos()")
529 g.P(" switch {")
530 g.P(" case x == nil:")
531 g.P(" return invalidNil")
532 g.P(" case secs < minTimestamp:")
533 g.P(" return invalidUnderflow")
534 g.P(" case secs > maxTimestamp:")
535 g.P(" return invalidOverflow")
536 g.P(" case nanos < 0 || nanos >= 1e9:")
537 g.P(" return invalidNanos")
538 g.P(" default:")
539 g.P(" return 0")
540 g.P(" }")
541 g.P("}")
542 g.P()
545 g.P("// New constructs a new Duration from the provided time.Duration.")
546 g.P("func New(d ", timePackage.Ident("Duration"), ") *Duration {")
547 g.P(" nanos := d.Nanoseconds()")
548 g.P(" secs := nanos / 1e9")
549 g.P(" nanos -= secs * 1e9")
550 g.P(" return &Duration{Seconds: int64(secs), Nanos: int32(nanos)}")
551 g.P("}")
552 g.P()
554 g.P("// AsDuration converts x to a time.Duration,")
555 g.P("// returning the closest duration value in the event of overflow.")
556 g.P("func (x *Duration) AsDuration() ", timePackage.Ident("Duration"), " {")
557 g.P(" secs := x.GetSeconds()")
558 g.P(" nanos := x.GetNanos()")
559 g.P(" d := ", timePackage.Ident("Duration"), "(secs) * ", timePackage.Ident("Second"))
560 …g.P(" overflow := d/", timePackage.Ident("Second"), " != ", timePackage.Ident("Duration"), "(secs)…
561 g.P(" d += ", timePackage.Ident("Duration"), "(nanos) * ", timePackage.Ident("Nanosecond"))
562 g.P(" overflow = overflow || (secs < 0 && nanos < 0 && d > 0)")
563 g.P(" overflow = overflow || (secs > 0 && nanos > 0 && d < 0)")
564 g.P(" if overflow {")
565 g.P(" switch {")
566 g.P(" case secs < 0:")
567 g.P(" return ", timePackage.Ident("Duration"), "(", mathPackage.Ident("MinInt64"), ")")
568 g.P(" case secs > 0:")
569 g.P(" return ", timePackage.Ident("Duration"), "(", mathPackage.Ident("MaxInt64"), ")")
570 g.P(" }")
571 g.P(" }")
572 g.P(" return d")
573 g.P("}")
574 g.P()
576 g.P("// IsValid reports whether the duration is valid.")
577 g.P("// It is equivalent to CheckValid == nil.")
578 g.P("func (x *Duration) IsValid() bool {")
579 g.P(" return x.check() == 0")
580 g.P("}")
581 g.P()
583 g.P("// CheckValid returns an error if the duration is invalid.")
584 g.P("// In particular, it checks whether the value is within the range of")
585 g.P("// -10000 years to +10000 years inclusive.")
586 g.P("// An error is reported for a nil Duration.")
587 g.P("func (x *Duration) CheckValid() error {")
588 g.P(" switch x.check() {")
589 g.P(" case invalidNil:")
590 g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid nil Duration\")")
591 g.P(" case invalidUnderflow:")
592 …g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"duration (%v) exceeds -10000 years\", x…
593 g.P(" case invalidOverflow:")
594 …g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"duration (%v) exceeds +10000 years\", x…
595 g.P(" case invalidNanosRange:")
596 …g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"duration (%v) has out-of-range nanos\",…
597 g.P(" case invalidNanosSign:")
598 …g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"duration (%v) has seconds and nanos wit…
599 g.P(" default:")
600 g.P(" return nil")
601 g.P(" }")
602 g.P("}")
603 g.P()
605 g.P("const (")
606 g.P(" _ = iota")
607 g.P(" invalidNil")
608 g.P(" invalidUnderflow")
609 g.P(" invalidOverflow")
610 g.P(" invalidNanosRange")
611 g.P(" invalidNanosSign")
612 g.P(")")
613 g.P()
615 g.P("func (x *Duration) check() uint {")
616 …g.P(" const absDuration = 315576000000 // 10000yr * 365.25day/yr * 24hr/day * 60min/hr * 60sec/min…
617 g.P(" secs := x.GetSeconds()")
618 g.P(" nanos := x.GetNanos()")
619 g.P(" switch {")
620 g.P(" case x == nil:")
621 g.P(" return invalidNil")
622 g.P(" case secs < -absDuration:")
623 g.P(" return invalidUnderflow")
624 g.P(" case secs > +absDuration:")
625 g.P(" return invalidOverflow")
626 g.P(" case nanos <= -1e9 || nanos >= +1e9:")
627 g.P(" return invalidNanosRange")
628 g.P(" case (secs > 0 && nanos < 0) || (secs < 0 && nanos > 0):")
629 g.P(" return invalidNanosSign")
630 g.P(" default:")
631 g.P(" return 0")
632 g.P(" }")
633 g.P("}")
634 g.P()
637 g.P("// NewStruct constructs a Struct from a general-purpose Go map.")
638 g.P("// The map keys must be valid UTF-8.")
639 g.P("// The map values are converted using NewValue.")
640 g.P("func NewStruct(v map[string]interface{}) (*Struct, error) {")
641 g.P(" x := &Struct{Fields: make(map[string]*Value, len(v))}")
642 g.P(" for k, v := range v {")
643 g.P(" if !", utf8Package.Ident("ValidString"), "(k) {")
644 …g.P(" return nil, ", protoimplPackage.Ident("X"), ".NewError(\"invalid UTF-8 in string: %q\", k)…
645 g.P(" }")
646 g.P(" var err error")
647 g.P(" x.Fields[k], err = NewValue(v)")
648 g.P(" if err != nil {")
649 g.P(" return nil, err")
650 g.P(" }")
651 g.P(" }")
652 g.P(" return x, nil")
653 g.P("}")
654 g.P()
656 g.P("// AsMap converts x to a general-purpose Go map.")
657 g.P("// The map values are converted by calling Value.AsInterface.")
658 g.P("func (x *Struct) AsMap() map[string]interface{} {")
659 g.P(" vs := make(map[string]interface{})")
660 g.P(" for k, v := range x.GetFields() {")
661 g.P(" vs[k] = v.AsInterface()")
662 g.P(" }")
663 g.P(" return vs")
664 g.P("}")
665 g.P()
667 g.P("func (x *Struct) MarshalJSON() ([]byte, error) {")
668 g.P(" return ", protojsonPackage.Ident("Marshal"), "(x)")
669 g.P("}")
670 g.P()
672 g.P("func (x *Struct) UnmarshalJSON(b []byte) error {")
673 g.P(" return ", protojsonPackage.Ident("Unmarshal"), "(b, x)")
674 g.P("}")
675 g.P()
678 g.P("// NewList constructs a ListValue from a general-purpose Go slice.")
679 g.P("// The slice elements are converted using NewValue.")
680 g.P("func NewList(v []interface{}) (*ListValue, error) {")
681 g.P(" x := &ListValue{Values: make([]*Value, len(v))}")
682 g.P(" for i, v := range v {")
683 g.P(" var err error")
684 g.P(" x.Values[i], err = NewValue(v)")
685 g.P(" if err != nil {")
686 g.P(" return nil, err")
687 g.P(" }")
688 g.P(" }")
689 g.P(" return x, nil")
690 g.P("}")
691 g.P()
693 g.P("// AsSlice converts x to a general-purpose Go slice.")
694 g.P("// The slice elements are converted by calling Value.AsInterface.")
695 g.P("func (x *ListValue) AsSlice() []interface{} {")
696 g.P(" vs := make([]interface{}, len(x.GetValues()))")
697 g.P(" for i, v := range x.GetValues() {")
698 g.P(" vs[i] = v.AsInterface()")
699 g.P(" }")
700 g.P(" return vs")
701 g.P("}")
702 g.P()
704 g.P("func (x *ListValue) MarshalJSON() ([]byte, error) {")
705 g.P(" return ", protojsonPackage.Ident("Marshal"), "(x)")
706 g.P("}")
707 g.P()
709 g.P("func (x *ListValue) UnmarshalJSON(b []byte) error {")
710 g.P(" return ", protojsonPackage.Ident("Unmarshal"), "(b, x)")
711 g.P("}")
712 g.P()
715 g.P("// NewValue constructs a Value from a general-purpose Go interface.")
716 g.P("//")
717 g.P("// ╔════════════════════════╤════════════════════════════════════════════╗")
718 g.P("// ║ Go type │ Conversion ║")
719 g.P("// ╠════════════════════════╪════════════════════════════════════════════╣")
720 g.P("// ║ nil │ stored as NullValue ║")
721 g.P("// ║ bool │ stored as BoolValue ║")
722 g.P("// ║ int, int32, int64 │ stored as NumberValue ║")
723 g.P("// ║ uint, uint32, uint64 │ stored as NumberValue ║")
724 g.P("// ║ float32, float64 │ stored as NumberValue ║")
725 g.P("// ║ string │ stored as StringValue; must be valid UTF-8 ║")
726 g.P("// ║ []byte │ stored as StringValue; base64-encoded ║")
727 g.P("// ║ map[string]interface{} │ stored as StructValue ║")
728 g.P("// ║ []interface{} │ stored as ListValue ║")
729 g.P("// ╚════════════════════════╧════════════════════════════════════════════╝")
730 g.P("//")
731 g.P("// When converting an int64 or uint64 to a NumberValue, numeric precision loss")
732 g.P("// is possible since they are stored as a float64.")
733 g.P("func NewValue(v interface{}) (*Value, error) {")
734 g.P(" switch v := v.(type) {")
735 g.P(" case nil:")
736 g.P(" return NewNullValue(), nil")
737 g.P(" case bool:")
738 g.P(" return NewBoolValue(v), nil")
739 g.P(" case int:")
740 g.P(" return NewNumberValue(float64(v)), nil")
741 g.P(" case int32:")
742 g.P(" return NewNumberValue(float64(v)), nil")
743 g.P(" case int64:")
744 g.P(" return NewNumberValue(float64(v)), nil")
745 g.P(" case uint:")
746 g.P(" return NewNumberValue(float64(v)), nil")
747 g.P(" case uint32:")
748 g.P(" return NewNumberValue(float64(v)), nil")
749 g.P(" case uint64:")
750 g.P(" return NewNumberValue(float64(v)), nil")
751 g.P(" case float32:")
752 g.P(" return NewNumberValue(float64(v)), nil")
753 g.P(" case float64:")
754 g.P(" return NewNumberValue(float64(v)), nil")
755 g.P(" case string:")
756 g.P(" if !", utf8Package.Ident("ValidString"), "(v) {")
757 …g.P(" return nil, ", protoimplPackage.Ident("X"), ".NewError(\"invalid UTF-8 in string: %q\", v)…
758 g.P(" }")
759 g.P(" return NewStringValue(v), nil")
760 g.P(" case []byte:")
761 g.P(" s := ", base64Package.Ident("StdEncoding"), ".EncodeToString(v)")
762 g.P(" return NewStringValue(s), nil")
763 g.P(" case map[string]interface{}:")
764 g.P(" v2, err := NewStruct(v)")
765 g.P(" if err != nil {")
766 g.P(" return nil, err")
767 g.P(" }")
768 g.P(" return NewStructValue(v2), nil")
769 g.P(" case []interface{}:")
770 g.P(" v2, err := NewList(v)")
771 g.P(" if err != nil {")
772 g.P(" return nil, err")
773 g.P(" }")
774 g.P(" return NewListValue(v2), nil")
775 g.P(" default:")
776 g.P(" return nil, ", protoimplPackage.Ident("X"), ".NewError(\"invalid type: %T\", v)")
777 g.P(" }")
778 g.P("}")
779 g.P()
781 g.P("// NewNullValue constructs a new null Value.")
782 g.P("func NewNullValue() *Value {")
783 g.P(" return &Value{Kind: &Value_NullValue{NullValue: NullValue_NULL_VALUE}}")
784 g.P("}")
785 g.P()
787 g.P("// NewBoolValue constructs a new boolean Value.")
788 g.P("func NewBoolValue(v bool) *Value {")
789 g.P(" return &Value{Kind: &Value_BoolValue{BoolValue: v}}")
790 g.P("}")
791 g.P()
793 g.P("// NewNumberValue constructs a new number Value.")
794 g.P("func NewNumberValue(v float64) *Value {")
795 g.P(" return &Value{Kind: &Value_NumberValue{NumberValue: v}}")
796 g.P("}")
797 g.P()
799 g.P("// NewStringValue constructs a new string Value.")
800 g.P("func NewStringValue(v string) *Value {")
801 g.P(" return &Value{Kind: &Value_StringValue{StringValue: v}}")
802 g.P("}")
803 g.P()
805 g.P("// NewStructValue constructs a new struct Value.")
806 g.P("func NewStructValue(v *Struct) *Value {")
807 g.P(" return &Value{Kind: &Value_StructValue{StructValue: v}}")
808 g.P("}")
809 g.P()
811 g.P("// NewListValue constructs a new list Value.")
812 g.P("func NewListValue(v *ListValue) *Value {")
813 g.P(" return &Value{Kind: &Value_ListValue{ListValue: v}}")
814 g.P("}")
815 g.P()
817 g.P("// AsInterface converts x to a general-purpose Go interface.")
818 g.P("//")
819 g.P("// Calling Value.MarshalJSON and \"encoding/json\".Marshal on this output produce")
820 g.P("// semantically equivalent JSON (assuming no errors occur).")
821 g.P("//")
822 g.P("// Floating-point values (i.e., \"NaN\", \"Infinity\", and \"-Infinity\") are")
823 g.P("// converted as strings to remain compatible with MarshalJSON.")
824 g.P("func (x *Value) AsInterface() interface{} {")
825 g.P(" switch v := x.GetKind().(type) {")
826 g.P(" case *Value_NumberValue:")
827 g.P(" if v != nil {")
828 g.P(" switch {")
829 g.P(" case ", mathPackage.Ident("IsNaN"), "(v.NumberValue):")
830 g.P(" return \"NaN\"")
831 g.P(" case ", mathPackage.Ident("IsInf"), "(v.NumberValue, +1):")
832 g.P(" return \"Infinity\"")
833 g.P(" case ", mathPackage.Ident("IsInf"), "(v.NumberValue, -1):")
834 g.P(" return \"-Infinity\"")
835 g.P(" default:")
836 g.P(" return v.NumberValue")
837 g.P(" }")
838 g.P(" }")
839 g.P(" case *Value_StringValue:")
840 g.P(" if v != nil {")
841 g.P(" return v.StringValue")
842 g.P(" }")
843 g.P(" case *Value_BoolValue:")
844 g.P(" if v != nil {")
845 g.P(" return v.BoolValue")
846 g.P(" }")
847 g.P(" case *Value_StructValue:")
848 g.P(" if v != nil {")
849 g.P(" return v.StructValue.AsMap()")
850 g.P(" }")
851 g.P(" case *Value_ListValue:")
852 g.P(" if v != nil {")
853 g.P(" return v.ListValue.AsSlice()")
854 g.P(" }")
855 g.P(" }")
856 g.P(" return nil")
857 g.P("}")
858 g.P()
860 g.P("func (x *Value) MarshalJSON() ([]byte, error) {")
861 g.P(" return ", protojsonPackage.Ident("Marshal"), "(x)")
862 g.P("}")
863 g.P()
865 g.P("func (x *Value) UnmarshalJSON(b []byte) error {")
866 g.P(" return ", protojsonPackage.Ident("Unmarshal"), "(b, x)")
867 g.P("}")
868 g.P()
871 g.P("// New constructs a field mask from a list of paths and verifies that")
872 g.P("// each one is valid according to the specified message type.")
873 g.P("func New(m ", protoPackage.Ident("Message"), ", paths ...string) (*FieldMask, error) {")
874 g.P(" x := new(FieldMask)")
875 g.P(" return x, x.Append(m, paths...)")
876 g.P("}")
877 g.P()
879 g.P("// Union returns the union of all the paths in the input field masks.")
880 g.P("func Union(mx *FieldMask, my *FieldMask, ms ...*FieldMask) *FieldMask {")
881 g.P(" var out []string")
882 g.P(" out = append(out, mx.GetPaths()...)")
883 g.P(" out = append(out, my.GetPaths()...)")
884 g.P(" for _, m := range ms {")
885 g.P(" out = append(out, m.GetPaths()...)")
886 g.P(" }")
887 g.P(" return &FieldMask{Paths: normalizePaths(out)}")
888 g.P("}")
889 g.P()
891 g.P("// Intersect returns the intersection of all the paths in the input field masks.")
892 g.P("func Intersect(mx *FieldMask, my *FieldMask, ms ...*FieldMask) *FieldMask {")
893 g.P(" var ss1, ss2 []string // reused buffers for performance")
894 g.P(" intersect := func(out, in []string) []string {")
895 g.P(" ss1 = normalizePaths(append(ss1[:0], in...))")
896 g.P(" ss2 = normalizePaths(append(ss2[:0], out...))")
897 g.P(" out = out[:0]")
898 g.P(" for i1, i2 := 0, 0; i1 < len(ss1) && i2 < len(ss2); {")
899 g.P(" switch s1, s2 := ss1[i1], ss2[i2]; {")
900 g.P(" case hasPathPrefix(s1, s2):")
901 g.P(" out = append(out, s1)")
902 g.P(" i1++")
903 g.P(" case hasPathPrefix(s2, s1):")
904 g.P(" out = append(out, s2)")
905 g.P(" i2++")
906 g.P(" case lessPath(s1, s2):")
907 g.P(" i1++")
908 g.P(" case lessPath(s2, s1):")
909 g.P(" i2++")
910 g.P(" }")
911 g.P(" }")
912 g.P(" return out")
913 g.P(" }")
914 g.P()
915 g.P(" out := Union(mx, my, ms...).GetPaths()")
916 g.P(" out = intersect(out, mx.GetPaths())")
917 g.P(" out = intersect(out, my.GetPaths())")
918 g.P(" for _, m := range ms {")
919 g.P(" out = intersect(out, m.GetPaths())")
920 g.P(" }")
921 g.P(" return &FieldMask{Paths: normalizePaths(out)}")
922 g.P("}")
923 g.P()
925 g.P("// IsValid reports whether all the paths are syntactically valid and")
926 g.P("// refer to known fields in the specified message type.")
927 g.P("// It reports false for a nil FieldMask.")
928 g.P("func (x *FieldMask) IsValid(m ", protoPackage.Ident("Message"), ") bool {")
929 g.P(" paths := x.GetPaths()")
930 g.P(" return x != nil && numValidPaths(m, paths) == len(paths)")
931 g.P("}")
932 g.P()
934 g.P("// Append appends a list of paths to the mask and verifies that each one")
935 g.P("// is valid according to the specified message type.")
936 g.P("// An invalid path is not appended and breaks insertion of subsequent paths.")
937 g.P("func (x *FieldMask) Append(m ", protoPackage.Ident("Message"), ", paths ...string) error {")
938 g.P(" numValid := numValidPaths(m, paths)")
939 g.P(" x.Paths = append(x.Paths, paths[:numValid]...)")
940 g.P(" paths = paths[numValid:]")
941 g.P(" if len(paths) > 0 {")
942 g.P(" name := m.ProtoReflect().Descriptor().FullName()")
943 …g.P(" return ", protoimplPackage.Ident("X"), ".NewError(\"invalid path %q for message %q\", paths…
944 g.P(" }")
945 g.P(" return nil")
946 g.P("}")
947 g.P()
949 g.P("func numValidPaths(m ", protoPackage.Ident("Message"), ", paths []string) int {")
950 g.P(" md0 := m.ProtoReflect().Descriptor()")
951 g.P(" for i, path := range paths {")
952 g.P(" md := md0")
953 g.P(" if !rangeFields(path, func(field string) bool {")
954 g.P(" // Search the field within the message.")
955 g.P(" if md == nil {")
956 g.P(" return false // not within a message")
957 g.P(" }")
958 g.P(" fd := md.Fields().ByName(", protoreflectPackage.Ident("Name"), "(field))")
959 g.P(" // The real field name of a group is the message name.")
960 g.P(" if fd == nil {")
961 …g.P(" gd := md.Fields().ByName(", protoreflectPackage.Ident("Name"), "(", stringsPackage.Ident(…
962 …g.P(" if gd != nil && gd.Kind() == ", protoreflectPackage.Ident("GroupKind"), " && string(gd.Me…
963 g.P(" fd = gd")
964 g.P(" }")
965 …g.P(" } else if fd.Kind() == ", protoreflectPackage.Ident("GroupKind"), " && string(fd.Message()…
966 g.P(" fd = nil")
967 g.P(" }")
968 g.P(" if fd == nil {")
969 g.P(" return false // message has does not have this field")
970 g.P(" }")
971 g.P()
972 g.P(" // Identify the next message to search within.")
973 g.P(" md = fd.Message() // may be nil")
974 g.P()
975 g.P(" // Repeated fields are only allowed at the last postion.")
976 g.P(" if fd.IsList() || fd.IsMap() {")
977 g.P(" md = nil")
978 g.P(" }")
979 g.P()
980 g.P(" return true")
981 g.P(" }) {")
982 g.P(" return i")
983 g.P(" }")
984 g.P(" }")
985 g.P(" return len(paths)")
986 g.P("}")
987 g.P()
989 g.P("// Normalize converts the mask to its canonical form where all paths are sorted")
990 g.P("// and redundant paths are removed.")
991 g.P("func (x *FieldMask) Normalize() {")
992 g.P(" x.Paths = normalizePaths(x.Paths)")
993 g.P("}")
994 g.P()
995 g.P("func normalizePaths(paths []string) []string {")
996 g.P(" ", sortPackage.Ident("Slice"), "(paths, func(i, j int) bool {")
997 g.P(" return lessPath(paths[i], paths[j])")
998 g.P(" })")
999 g.P()
1000 g.P(" // Elide any path that is a prefix match on the previous.")
1001 g.P(" out := paths[:0]")
1002 g.P(" for _, path := range paths {")
1003 g.P(" if len(out) > 0 && hasPathPrefix(path, out[len(out)-1]) {")
1004 g.P(" continue")
1005 g.P(" }")
1006 g.P(" out = append(out, path)")
1007 g.P(" }")
1008 g.P(" return out")
1009 g.P("}")
1010 g.P()
1012 g.P("// hasPathPrefix is like strings.HasPrefix, but further checks for either")
1013 g.P("// an exact matche or that the prefix is delimited by a dot.")
1014 g.P("func hasPathPrefix(path, prefix string) bool {")
1015 …g.P(" return ", stringsPackage.Ident("HasPrefix"), "(path, prefix) && (len(path) == len(prefix) ||…
1016 g.P("}")
1017 g.P()
1019 g.P("// lessPath is a lexicographical comparison where dot is specially treated")
1020 g.P("// as the smallest symbol.")
1021 g.P("func lessPath(x, y string) bool {")
1022 g.P(" for i := 0; i < len(x) && i < len(y); i++ {")
1023 g.P(" if x[i] != y[i] {")
1024 g.P(" return (x[i] - '.') < (y[i] - '.')")
1025 g.P(" }")
1026 g.P(" }")
1027 g.P(" return len(x) < len(y)")
1028 g.P("}")
1029 g.P()
1031 g.P("// rangeFields is like strings.Split(path, \".\"), but avoids allocations by")
1032 g.P("// iterating over each field in place and calling a iterator function.")
1033 g.P("func rangeFields(path string, f func(field string) bool) bool {")
1034 g.P(" for {")
1035 g.P(" var field string")
1036 g.P(" if i := ", stringsPackage.Ident("IndexByte"), "(path, '.'); i >= 0 {")
1037 g.P(" field, path = path[:i], path[i:]")
1038 g.P(" } else {")
1039 g.P(" field, path = path, \"\"")
1040 g.P(" }")
1041 g.P()
1042 g.P(" if !f(field) {")
1043 g.P(" return false")
1044 g.P(" }")
1045 g.P()
1046 g.P(" if len(path) == 0 {")
1047 g.P(" return true")
1048 g.P(" }")
1049 g.P(" path = ", stringsPackage.Ident("TrimPrefix"), "(path, \".\")")
1050 g.P(" }")
1051 g.P("}")
1052 g.P()
1074 g.P("// ", funcName, " stores v in a new ", m.GoIdent, " and returns a pointer to it.")
1075 g.P("func ", funcName, "(v ", typeName, ") *", m.GoIdent, " {")
1076 g.P(" return &", m.GoIdent, "{Value: v}")
1077 g.P("}")
1078 g.P()