Scott Baker | 105df15 | 2020-04-13 15:55:14 -0700 | [diff] [blame^] | 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 | |
| 5 | package proto |
| 6 | |
| 7 | import "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 | |
| 20 | func 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 | } |