reset.go 1018 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  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 (
  6. "fmt"
  7. "google.golang.org/protobuf/reflect/protoreflect"
  8. )
  9. // Reset clears every field in the message.
  10. // The resulting message shares no observable memory with its previous state
  11. // other than the memory for the message itself.
  12. func Reset(m Message) {
  13. if mr, ok := m.(interface{ Reset() }); ok && hasProtoMethods {
  14. mr.Reset()
  15. return
  16. }
  17. resetMessage(m.ProtoReflect())
  18. }
  19. func resetMessage(m protoreflect.Message) {
  20. if !m.IsValid() {
  21. panic(fmt.Sprintf("cannot reset invalid %v message", m.Descriptor().FullName()))
  22. }
  23. // Clear all known fields.
  24. fds := m.Descriptor().Fields()
  25. for i := 0; i < fds.Len(); i++ {
  26. m.Clear(fds.Get(i))
  27. }
  28. // Clear extension fields.
  29. m.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool {
  30. m.Clear(fd)
  31. return true
  32. })
  33. // Clear unknown fields.
  34. m.SetUnknown(nil)
  35. }