weak.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. pref "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 pref.FieldNumber) (pref.ProtoMessage, bool) {
  16. m, ok := w[int32(num)]
  17. return m, ok
  18. }
  19. func (w *weakFields) set(num pref.FieldNumber, m pref.ProtoMessage) {
  20. if *w == nil {
  21. *w = make(weakFields)
  22. }
  23. (*w)[int32(num)] = m
  24. }
  25. func (w *weakFields) clear(num pref.FieldNumber) {
  26. delete(*w, int32(num))
  27. }
  28. func (Export) HasWeak(w WeakFields, num pref.FieldNumber) bool {
  29. _, ok := w[int32(num)]
  30. return ok
  31. }
  32. func (Export) ClearWeak(w *WeakFields, num pref.FieldNumber) {
  33. delete(*w, int32(num))
  34. }
  35. func (Export) GetWeak(w WeakFields, num pref.FieldNumber, name pref.FullName) pref.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 pref.FieldNumber, name pref.FullName, m pref.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. }