defaults.go 1.6 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. "google.golang.org/protobuf/reflect/protoreflect"
  7. )
  8. // SetDefaults sets unpopulated scalar fields to their default values.
  9. // Fields within a oneof are not set even if they have a default value.
  10. // SetDefaults is recursively called upon any populated message fields.
  11. func SetDefaults(m Message) {
  12. if m != nil {
  13. setDefaults(MessageReflect(m))
  14. }
  15. }
  16. func setDefaults(m protoreflect.Message) {
  17. fds := m.Descriptor().Fields()
  18. for i := 0; i < fds.Len(); i++ {
  19. fd := fds.Get(i)
  20. if !m.Has(fd) {
  21. if fd.HasDefault() && fd.ContainingOneof() == nil {
  22. v := fd.Default()
  23. if fd.Kind() == protoreflect.BytesKind {
  24. v = protoreflect.ValueOf(append([]byte(nil), v.Bytes()...)) // copy the default bytes
  25. }
  26. m.Set(fd, v)
  27. }
  28. continue
  29. }
  30. }
  31. m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
  32. switch {
  33. // Handle singular message.
  34. case fd.Cardinality() != protoreflect.Repeated:
  35. if fd.Message() != nil {
  36. setDefaults(m.Get(fd).Message())
  37. }
  38. // Handle list of messages.
  39. case fd.IsList():
  40. if fd.Message() != nil {
  41. ls := m.Get(fd).List()
  42. for i := 0; i < ls.Len(); i++ {
  43. setDefaults(ls.Get(i).Message())
  44. }
  45. }
  46. // Handle map of messages.
  47. case fd.IsMap():
  48. if fd.MapValue().Message() != nil {
  49. ms := m.Get(fd).Map()
  50. ms.Range(func(_ protoreflect.MapKey, v protoreflect.Value) bool {
  51. setDefaults(v.Message())
  52. return true
  53. })
  54. }
  55. }
  56. return true
  57. })
  58. }