defaults.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. pref "google.golang.org/protobuf/reflect/protoreflect"
  7. "google.golang.org/protobuf/runtime/protoimpl"
  8. )
  9. // SetDefaults sets unset protocol buffer fields to their default values.
  10. // It only modifies fields that are both unset and have defined defaults.
  11. // It recursively sets default values in any non-nil sub-messages.
  12. // It does not descend into extension fields that are sub-messages.
  13. func SetDefaults(m Message) {
  14. setDefaults(protoimpl.X.MessageOf(m))
  15. }
  16. func setDefaults(m pref.Message) {
  17. fieldDescs := m.Descriptor().Fields()
  18. for i := 0; i < fieldDescs.Len(); i++ {
  19. fd := fieldDescs.Get(i)
  20. if !m.Has(fd) {
  21. if fd.HasDefault() {
  22. v := fd.Default()
  23. if fd.Kind() == pref.BytesKind {
  24. v = pref.ValueOf(append([]byte(nil), v.Bytes()...)) // copy the default bytes
  25. }
  26. m.Set(fd, v)
  27. }
  28. continue
  29. }
  30. switch {
  31. // Handle singular message.
  32. case fd.Cardinality() != pref.Repeated:
  33. if k := fd.Kind(); k == pref.MessageKind || k == pref.GroupKind {
  34. setDefaults(m.Get(fd).Message())
  35. }
  36. // Handle list of messages.
  37. case !fd.IsMap():
  38. if k := fd.Kind(); k == pref.MessageKind || k == pref.GroupKind {
  39. ls := m.Get(fd).List()
  40. for i := 0; i < ls.Len(); i++ {
  41. setDefaults(ls.Get(i).Message())
  42. }
  43. }
  44. // Handle map of messages.
  45. default:
  46. k := fd.Message().Fields().ByNumber(2).Kind()
  47. if k == pref.MessageKind || k == pref.GroupKind {
  48. ms := m.Get(fd).Map()
  49. ms.Range(func(_ pref.MapKey, v pref.Value) bool {
  50. setDefaults(v.Message())
  51. return true
  52. })
  53. }
  54. }
  55. }
  56. // NOTE: Historically, this function has never set the defaults for
  57. // extension fields, nor recursively visited sub-messages of such fields.
  58. }