blob: 22048bc1fab7381dd3e0af861c6f4f3b7ff2d8d8 [file] [log] [blame]
Scott Baker105df152020-04-13 15:55:14 -07001// 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
5package proto
6
7import "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.
12func Reset(m Message) {
13 if mr, ok := m.(interface{ Reset() }); ok && hasProtoMethods {
14 mr.Reset()
15 return
16 }
17 resetMessage(m.ProtoReflect())
18}
19
20func resetMessage(m protoreflect.Message) {
21 if !m.IsValid() {
22 panic("cannot reset invalid message")
23 }
24
25 // Clear all known fields.
26 fds := m.Descriptor().Fields()
27 for i := 0; i < fds.Len(); i++ {
28 m.Clear(fds.Get(i))
29 }
30
31 // Clear extension fields.
32 m.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool {
33 m.Clear(fd)
34 return true
35 })
36
37 // Clear unknown fields.
38 m.SetUnknown(nil)
39}