You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

39 lines
962 B

  1. // Copyright 2019 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package proto
  5. import "google.golang.org/protobuf/reflect/protoreflect"
  6. // Reset clears every field in the message.
  7. // The resulting message shares no observable memory with its previous state
  8. // other than the memory for the message itself.
  9. func Reset(m Message) {
  10. if mr, ok := m.(interface{ Reset() }); ok && hasProtoMethods {
  11. mr.Reset()
  12. return
  13. }
  14. resetMessage(m.ProtoReflect())
  15. }
  16. func resetMessage(m protoreflect.Message) {
  17. if !m.IsValid() {
  18. panic("cannot reset invalid message")
  19. }
  20. // Clear all known fields.
  21. fds := m.Descriptor().Fields()
  22. for i := 0; i < fds.Len(); i++ {
  23. m.Clear(fds.Get(i))
  24. }
  25. // Clear extension fields.
  26. m.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool {
  27. m.Clear(fd)
  28. return true
  29. })
  30. // Clear unknown fields.
  31. m.SetUnknown(nil)
  32. }