weak.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. "reflect"
  7. pref "google.golang.org/protobuf/reflect/protoreflect"
  8. )
  9. // weakFields adds methods to the exported WeakFields type for internal use.
  10. //
  11. // The exported type is an alias to an unnamed type, so methods can't be
  12. // defined directly on it.
  13. type weakFields WeakFields
  14. func (w *weakFields) get(num pref.FieldNumber) (_ pref.ProtoMessage, ok bool) {
  15. if *w == nil {
  16. return nil, false
  17. }
  18. m, ok := (*w)[int32(num)]
  19. if !ok {
  20. return nil, false
  21. }
  22. // As a legacy quirk, consider a typed nil to be unset.
  23. //
  24. // TODO: Consider fixing the generated set methods to clear the field
  25. // when provided with a typed nil.
  26. if v := reflect.ValueOf(m); v.Kind() == reflect.Ptr && v.IsNil() {
  27. return nil, false
  28. }
  29. return Export{}.ProtoMessageV2Of(m), true
  30. }
  31. func (w *weakFields) set(num pref.FieldNumber, m pref.ProtoMessage) {
  32. if *w == nil {
  33. *w = make(weakFields)
  34. }
  35. (*w)[int32(num)] = Export{}.ProtoMessageV1Of(m)
  36. }
  37. func (w *weakFields) clear(num pref.FieldNumber) {
  38. delete(*w, int32(num))
  39. }