You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 rivejä
2.0 KiB

  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 impl
  5. import (
  6. "fmt"
  7. "google.golang.org/protobuf/reflect/protoreflect"
  8. "google.golang.org/protobuf/reflect/protoregistry"
  9. )
  10. // weakFields adds methods to the exported WeakFields type for internal use.
  11. //
  12. // The exported type is an alias to an unnamed type, so methods can't be
  13. // defined directly on it.
  14. type weakFields WeakFields
  15. func (w weakFields) get(num protoreflect.FieldNumber) (protoreflect.ProtoMessage, bool) {
  16. m, ok := w[int32(num)]
  17. return m, ok
  18. }
  19. func (w *weakFields) set(num protoreflect.FieldNumber, m protoreflect.ProtoMessage) {
  20. if *w == nil {
  21. *w = make(weakFields)
  22. }
  23. (*w)[int32(num)] = m
  24. }
  25. func (w *weakFields) clear(num protoreflect.FieldNumber) {
  26. delete(*w, int32(num))
  27. }
  28. func (Export) HasWeak(w WeakFields, num protoreflect.FieldNumber) bool {
  29. _, ok := w[int32(num)]
  30. return ok
  31. }
  32. func (Export) ClearWeak(w *WeakFields, num protoreflect.FieldNumber) {
  33. delete(*w, int32(num))
  34. }
  35. func (Export) GetWeak(w WeakFields, num protoreflect.FieldNumber, name protoreflect.FullName) protoreflect.ProtoMessage {
  36. if m, ok := w[int32(num)]; ok {
  37. return m
  38. }
  39. mt, _ := protoregistry.GlobalTypes.FindMessageByName(name)
  40. if mt == nil {
  41. panic(fmt.Sprintf("message %v for weak field is not linked in", name))
  42. }
  43. return mt.Zero().Interface()
  44. }
  45. func (Export) SetWeak(w *WeakFields, num protoreflect.FieldNumber, name protoreflect.FullName, m protoreflect.ProtoMessage) {
  46. if m != nil {
  47. mt, _ := protoregistry.GlobalTypes.FindMessageByName(name)
  48. if mt == nil {
  49. panic(fmt.Sprintf("message %v for weak field is not linked in", name))
  50. }
  51. if mt != m.ProtoReflect().Type() {
  52. panic(fmt.Sprintf("invalid message type for weak field: got %T, want %T", m, mt.Zero().Interface()))
  53. }
  54. }
  55. if m == nil || !m.ProtoReflect().IsValid() {
  56. delete(*w, int32(num))
  57. return
  58. }
  59. if *w == nil {
  60. *w = make(weakFields)
  61. }
  62. (*w)[int32(num)] = m
  63. }