reflect/protoreflect: add List.AppendMutable and Map.Mutable
Add methods to add a new, mutable message to a list or map, matching the
existing Message.Mutable.
These methods are purely a convenience, as each can be implemented in
terms of the existing interface.
Change-Id: I889c20fe37ea0f2a566555212e99e6378fb9fe1d
Reviewed-on: https://go-review.googlesource.com/c/protobuf/+/220117
Reviewed-by: Joe Tsai <joetsai@google.com>
diff --git a/internal/impl/convert_list.go b/internal/impl/convert_list.go
index 1c86942..fe9384a 100644
--- a/internal/impl/convert_list.go
+++ b/internal/impl/convert_list.go
@@ -119,6 +119,14 @@
func (ls *listReflect) Append(v pref.Value) {
ls.v.Elem().Set(reflect.Append(ls.v.Elem(), ls.conv.GoValueOf(v)))
}
+func (ls *listReflect) AppendMutable() pref.Value {
+ if _, ok := ls.conv.(*messageConverter); !ok {
+ panic("invalid AppendMutable on list with non-message type")
+ }
+ v := ls.NewElement()
+ ls.Append(v)
+ return v
+}
func (ls *listReflect) Truncate(i int) {
ls.v.Elem().Set(ls.v.Elem().Slice(0, i))
}
diff --git a/internal/impl/convert_map.go b/internal/impl/convert_map.go
index fcb1450..3ef36d3 100644
--- a/internal/impl/convert_map.go
+++ b/internal/impl/convert_map.go
@@ -89,6 +89,17 @@
rk := ms.keyConv.GoValueOf(k.Value())
ms.v.SetMapIndex(rk, reflect.Value{})
}
+func (ms *mapReflect) Mutable(k pref.MapKey) pref.Value {
+ if _, ok := ms.valConv.(*messageConverter); !ok {
+ panic("invalid Mutable on map with non-message value type")
+ }
+ v := ms.Get(k)
+ if !v.IsValid() {
+ v = ms.NewValue()
+ ms.Set(k, v)
+ }
+ return v
+}
func (ms *mapReflect) Range(f func(pref.MapKey, pref.Value) bool) {
iter := mapRange(ms.v)
for iter.Next() {