isinit.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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/internal/errors"
  7. "google.golang.org/protobuf/reflect/protoreflect"
  8. )
  9. // IsInitialized returns an error if any required fields in m are not set.
  10. func IsInitialized(m Message) error {
  11. return isInitialized(m.ProtoReflect())
  12. }
  13. // IsInitialized returns an error if any required fields in m are not set.
  14. func isInitialized(m protoreflect.Message) error {
  15. if methods := protoMethods(m); methods != nil && methods.IsInitialized != nil {
  16. return methods.IsInitialized(m)
  17. }
  18. return isInitializedSlow(m)
  19. }
  20. func isInitializedSlow(m protoreflect.Message) error {
  21. md := m.Descriptor()
  22. fds := md.Fields()
  23. for i, nums := 0, md.RequiredNumbers(); i < nums.Len(); i++ {
  24. fd := fds.ByNumber(nums.Get(i))
  25. if !m.Has(fd) {
  26. return errors.RequiredNotSet(string(fd.FullName()))
  27. }
  28. }
  29. var err error
  30. m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
  31. switch {
  32. case fd.IsList():
  33. if fd.Message() == nil {
  34. return true
  35. }
  36. for i, list := 0, v.List(); i < list.Len() && err == nil; i++ {
  37. err = isInitialized(list.Get(i).Message())
  38. }
  39. case fd.IsMap():
  40. if fd.MapValue().Message() == nil {
  41. return true
  42. }
  43. v.Map().Range(func(key protoreflect.MapKey, v protoreflect.Value) bool {
  44. err = isInitialized(v.Message())
  45. return err == nil
  46. })
  47. default:
  48. if fd.Message() == nil {
  49. return true
  50. }
  51. err = isInitialized(v.Message())
  52. }
  53. return err == nil
  54. })
  55. return err
  56. }