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