common.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. // TODO: This file exists to provide the illusion to other source files that
  6. // they live within the real proto package by providing functions and types
  7. // that they would otherwise be able to call directly.
  8. import (
  9. "fmt"
  10. "reflect"
  11. "google.golang.org/protobuf/runtime/protoiface"
  12. "google.golang.org/protobuf/runtime/protoimpl"
  13. )
  14. type (
  15. Message = protoiface.MessageV1
  16. ExtensionDesc = protoimpl.ExtensionInfo
  17. )
  18. // RequiredNotSetError is an error type returned by either Marshal or Unmarshal.
  19. // Marshal reports this when a required field is not initialized.
  20. // Unmarshal reports this when a required field is missing from the input data.
  21. type RequiredNotSetError struct{ field string }
  22. func (e *RequiredNotSetError) Error() string {
  23. if e.field == "" {
  24. return fmt.Sprintf("proto: required field not set")
  25. }
  26. return fmt.Sprintf("proto: required field %q not set", e.field)
  27. }
  28. func (e *RequiredNotSetError) RequiredNotSet() bool {
  29. return true
  30. }
  31. type errorMask uint8
  32. const (
  33. _ errorMask = (1 << iota) / 2
  34. errInvalidUTF8
  35. errRequiredNotSet
  36. )
  37. type errorsList = []error
  38. var errorsListType = reflect.TypeOf(errorsList{})
  39. // nonFatalErrors returns an errorMask identifying V2 non-fatal errors.
  40. func nonFatalErrors(err error) errorMask {
  41. verr := reflect.ValueOf(err)
  42. if !verr.IsValid() {
  43. return 0
  44. }
  45. if !verr.Type().AssignableTo(errorsListType) {
  46. return 0
  47. }
  48. errs := verr.Convert(errorsListType).Interface().(errorsList)
  49. var ret errorMask
  50. for _, e := range errs {
  51. switch e.(type) {
  52. case interface{ RequiredNotSet() bool }:
  53. ret |= errRequiredNotSet
  54. case interface{ InvalidUTF8() bool }:
  55. ret |= errInvalidUTF8
  56. }
  57. }
  58. return ret
  59. }