2019-04-05 20:31:40 +00:00
|
|
|
// Copyright 2019 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style.
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package proto
|
|
|
|
|
|
|
|
import (
|
2019-05-14 06:55:40 +00:00
|
|
|
"google.golang.org/protobuf/internal/errors"
|
2019-07-11 06:14:31 +00:00
|
|
|
"google.golang.org/protobuf/reflect/protoreflect"
|
2019-04-05 20:31:40 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// IsInitialized returns an error if any required fields in m are not set.
|
|
|
|
func IsInitialized(m Message) error {
|
2019-07-11 06:14:31 +00:00
|
|
|
return isInitialized(m.ProtoReflect())
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsInitialized returns an error if any required fields in m are not set.
|
|
|
|
func isInitialized(m protoreflect.Message) error {
|
2019-04-05 20:31:40 +00:00
|
|
|
if methods := protoMethods(m); methods != nil && methods.IsInitialized != nil {
|
2019-07-09 18:40:49 +00:00
|
|
|
return methods.IsInitialized(m)
|
2019-04-05 20:31:40 +00:00
|
|
|
}
|
2019-07-11 06:14:31 +00:00
|
|
|
return isInitializedSlow(m)
|
2019-04-05 20:31:40 +00:00
|
|
|
}
|
|
|
|
|
2019-07-11 06:14:31 +00:00
|
|
|
func isInitializedSlow(m protoreflect.Message) error {
|
2019-05-01 19:29:25 +00:00
|
|
|
md := m.Descriptor()
|
2019-04-26 06:48:08 +00:00
|
|
|
fds := md.Fields()
|
2019-04-05 20:31:40 +00:00
|
|
|
for i, nums := 0, md.RequiredNumbers(); i < nums.Len(); i++ {
|
2019-04-26 06:48:08 +00:00
|
|
|
fd := fds.ByNumber(nums.Get(i))
|
|
|
|
if !m.Has(fd) {
|
2019-07-09 18:40:49 +00:00
|
|
|
return errors.RequiredNotSet(string(fd.FullName()))
|
2019-04-05 20:31:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
var err error
|
2019-07-11 06:14:31 +00:00
|
|
|
m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
|
2019-04-26 06:48:08 +00:00
|
|
|
switch {
|
|
|
|
case fd.IsList():
|
|
|
|
if fd.Message() == nil {
|
2019-04-05 20:31:40 +00:00
|
|
|
return true
|
|
|
|
}
|
2019-04-26 06:48:08 +00:00
|
|
|
for i, list := 0, v.List(); i < list.Len() && err == nil; i++ {
|
2019-07-11 06:14:31 +00:00
|
|
|
err = isInitialized(list.Get(i).Message())
|
2019-04-05 20:31:40 +00:00
|
|
|
}
|
2019-04-26 06:48:08 +00:00
|
|
|
case fd.IsMap():
|
|
|
|
if fd.MapValue().Message() == nil {
|
|
|
|
return true
|
|
|
|
}
|
2019-07-11 06:14:31 +00:00
|
|
|
v.Map().Range(func(key protoreflect.MapKey, v protoreflect.Value) bool {
|
|
|
|
err = isInitialized(v.Message())
|
2019-05-13 21:32:56 +00:00
|
|
|
return err == nil
|
|
|
|
})
|
2019-04-05 20:31:40 +00:00
|
|
|
default:
|
2019-04-26 06:48:08 +00:00
|
|
|
if fd.Message() == nil {
|
|
|
|
return true
|
|
|
|
}
|
2019-07-11 06:14:31 +00:00
|
|
|
err = isInitialized(v.Message())
|
2019-04-05 20:31:40 +00:00
|
|
|
}
|
|
|
|
return err == nil
|
|
|
|
})
|
|
|
|
return err
|
|
|
|
}
|