gitea

Development moved to Codeberg

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 62
  63. 63
  64. 64
  65. 65
  66. 66
  67. 67
  68. 68
  69. 69
  70. 70
  71. 71
  72. 72
  73. 73
  74. 74
  75. 75
  76. 76
  77. 77
  78. 78
// 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 proto

import (
	protoV2 "google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/runtime/protoiface"
)

// Size returns the size in bytes of the wire-format encoding of m.
func Size(m Message) int {
	if m == nil {
		return 0
	}
	mi := MessageV2(m)
	return protoV2.Size(mi)
}

// Marshal returns the wire-format encoding of m.
func Marshal(m Message) ([]byte, error) {
	b, err := marshalAppend(nil, m, false)
	if b == nil {
		b = zeroBytes
	}
	return b, err
}

var zeroBytes = make([]byte, 0, 0)

func marshalAppend(buf []byte, m Message, deterministic bool) ([]byte, error) {
	if m == nil {
		return nil, ErrNil
	}
	mi := MessageV2(m)
	nbuf, err := protoV2.MarshalOptions{
		Deterministic: deterministic,
		AllowPartial:  true,
	}.MarshalAppend(buf, mi)
	if err != nil {
		return buf, err
	}
	if len(buf) == len(nbuf) {
		if !mi.ProtoReflect().IsValid() {
			return buf, ErrNil
		}
	}
	return nbuf, checkRequiredNotSet(mi)
}

// Unmarshal parses a wire-format message in b and places the decoded results in m.
//
// Unmarshal resets m before starting to unmarshal, so any existing data in m is always
// removed. Use UnmarshalMerge to preserve and append to existing data.
func Unmarshal(b []byte, m Message) error {
	m.Reset()
	return UnmarshalMerge(b, m)
}

// UnmarshalMerge parses a wire-format message in b and places the decoded results in m.
func UnmarshalMerge(b []byte, m Message) error {
	mi := MessageV2(m)
	out, err := protoV2.UnmarshalOptions{
		AllowPartial: true,
		Merge:        true,
	}.UnmarshalState(protoiface.UnmarshalInput{
		Buf:     b,
		Message: mi.ProtoReflect(),
	})
	if err != nil {
		return err
	}
	if out.Flags&protoiface.UnmarshalInitialized > 0 {
		return nil
	}
	return checkRequiredNotSet(mi)
}