Copilot commented on code in PR #3788:
URL: https://github.com/apache/thrift/pull/3788#discussion_r3917472712


##########
compiler/cpp/src/thrift/generate/t_go_generator.cc:
##########
@@ -4832,4 +4854,6 @@ THRIFT_REGISTER_GENERATOR(go, "Go",
                           "    read_write_private\n"
                           "                     Make read/write methods 
private, default is public Read/Write\n"
                           "    skip_remote\n"
-                          "                     Skip the generating of -remote 
folders for the client binaries for services\n")
+                          "                     Skip the generating of -remote 
folders for the client binaries for services\n"
+                          "    struct_key_entries\n"
+                          "                     Generate maps keyed by a 
struct as []thrift.MapEntry[*K, V] instead of map[*K]V\n")

Review Comment:
   The generator option help text says "maps keyed by a struct", but the 
implementation (and README) also applies to exceptions and unions (unions are 
treated as structs in the AST). Updating the help string avoids user confusion 
about which key types are affected.



##########
lib/go/test/tests/struct_key_test.go:
##########
@@ -0,0 +1,163 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package tests
+
+import (
+       "context"
+       "errors"
+       "testing"
+
+       "github.com/apache/thrift/lib/go/test/gopath/src/structkeytest"
+       "github.com/apache/thrift/lib/go/thrift"
+)
+
+func newStructKeyStruct() *structkeytest.StructKeyStruct {
+       s := structkeytest.NewStructKeyStruct()
+       s.ByKey = []thrift.MapEntry[*structkeytest.Key, string]{
+               {Key: &structkeytest.Key{ID: 1, Name: "one"}, Value: "1"},
+               {Key: &structkeytest.Key{ID: 2, Name: "two"}, Value: "2"},
+       }
+       s.ByErr = []thrift.MapEntry[*structkeytest.KeyErr, int32]{
+               {Key: &structkeytest.KeyErr{Msg: "boom"}, Value: 7},
+       }
+       // A map with a hashable key stays a Go map under the option.
+       s.Plain = map[string]int32{"a": 1}
+       num := int32(9)
+       text := "nine"
+       s.ByUnion = []thrift.MapEntry[*structkeytest.KeyUnion, int32]{
+               {Key: &structkeytest.KeyUnion{Num: &num}, Value: 1},
+               {Key: &structkeytest.KeyUnion{Text: &text}, Value: 2},
+       }
+       // A typedef of a struct resolves to the struct pointer, because the
+       // generated "type KeyAlias *Key" has no methods of its own.
+       s.ByAlias = []thrift.MapEntry[*structkeytest.Key, string]{
+               {Key: &structkeytest.Key{ID: 3, Name: "three"}, Value: "3"},
+       }
+       s.Nested = [][]thrift.MapEntry[*structkeytest.Key, string]{
+               {{Key: &structkeytest.Key{ID: 4, Name: "four"}, Value: "4"}},
+               {},
+       }
+       s.ValueAlsoKeyed = []thrift.MapEntry[*structkeytest.Key, 
[]thrift.MapEntry[*structkeytest.Key, int32]]{
+               {
+                       Key:   &structkeytest.Key{ID: 5, Name: "outer"},
+                       Value: []thrift.MapEntry[*structkeytest.Key, 
int32]{{Key: &structkeytest.Key{ID: 6, Name: "inner"}, Value: 6}},
+               },
+       }
+       s.Validated = []thrift.MapEntry[*structkeytest.ValidatedKey, string]{
+               {Key: &structkeytest.ValidatedKey{ID: 1}, Value: "ok"},
+       }
+       return s
+}
+
+func TestStructKeyRoundTrip(t *testing.T) {
+       for label, factory := range map[string]thrift.TProtocolFactory{
+               "binary":  thrift.NewTBinaryProtocolFactoryConf(nil),
+               "compact": thrift.NewTCompactProtocolFactoryConf(nil),
+               "json":    thrift.NewTJSONProtocolFactory(),
+       } {
+               t.Run(label, func(t *testing.T) {
+                       ctx := context.Background()
+                       src := newStructKeyStruct()
+                       serializer := thrift.NewTSerializer()
+                       serializer.Protocol = 
factory.GetProtocol(serializer.Transport)
+                       data, err := serializer.Write(ctx, src)
+                       if err != nil {
+                               t.Fatalf("write: %v", err)
+                       }
+                       dst := structkeytest.NewStructKeyStruct()
+                       deserializer := thrift.NewTDeserializer()
+                       deserializer.Protocol = 
factory.GetProtocol(deserializer.Transport)
+                       if err := deserializer.Read(ctx, dst, data); err != nil 
{
+                               t.Fatalf("read: %v", err)
+                       }
+                       // Keys are fresh allocations after decoding, so this 
only holds if
+                       // Equals compares key contents rather than pointer 
identity.
+                       if !src.Equals(dst) {
+                               t.Errorf("decoded struct not equal to 
original:\n src=%v\n dst=%v", src, dst)
+                       }
+               })
+       }
+}
+
+func TestStructKeyWriteRejectsDuplicateKeys(t *testing.T) {
+       s := newStructKeyStruct()
+       // Distinct pointers with equal contents are the same key.
+       s.ByKey[1].Key = &structkeytest.Key{ID: 1, Name: "one"}
+       _, err := thrift.NewTSerializer().Write(context.Background(), s)
+       var perr thrift.TProtocolException
+       if !errors.As(err, &perr) || perr.TypeId() != thrift.INVALID_DATA {
+               t.Fatalf("expected INVALID_DATA protocol exception for 
duplicate keys, got %v", err)
+       }
+}
+
+func TestStructKeyEqualsDetectsKeyDifference(t *testing.T) {
+       tests := map[string]func(s *structkeytest.StructKeyStruct){
+               "struct key":       func(s *structkeytest.StructKeyStruct) { 
s.ByKey[1].Key.Name = "deux" },
+               "map value":        func(s *structkeytest.StructKeyStruct) { 
s.ByKey[1].Value = "changed" },
+               "exception key":    func(s *structkeytest.StructKeyStruct) { 
s.ByErr[0].Key.Msg = "different" },
+               "union key":        func(s *structkeytest.StructKeyStruct) { 
*s.ByUnion[0].Key.Num = 10 },
+               "typedef key":      func(s *structkeytest.StructKeyStruct) { 
s.ByAlias[0].Key.ID = 30 },
+               "nested key":       func(s *structkeytest.StructKeyStruct) { 
s.Nested[0][0].Key.ID = 40 },
+               "keyed value key":  func(s *structkeytest.StructKeyStruct) { 
s.ValueAlsoKeyed[0].Value[0].Key.ID = 60 },
+               "entry order only": func(s *structkeytest.StructKeyStruct) { 
s.ByKey[0], s.ByKey[1] = s.ByKey[1], s.ByKey[0] },
+       }
+       a := newStructKeyStruct()
+       for name, mutate := range tests {
+               t.Run(name, func(t *testing.T) {
+                       b := newStructKeyStruct()
+                       if !a.Equals(b) {
+                               t.Fatal("identical structs must be equal")
+                       }
+                       mutate(b)
+                       if a.Equals(b) {
+                               t.Error("expected structs to differ")
+                       }
+               })
+       }
+}
+
+func TestStructKeyValidateChecksKeys(t *testing.T) {
+       s := newStructKeyStruct()
+       if err := s.Validate(); err != nil {
+               t.Fatalf("valid struct rejected: %v", err)
+       }
+       // vt.key.skip = "false" runs the key's own validator over every entry.
+       s.Validated[0].Key.ID = 0
+       err := s.Validate()
+       var aerr thrift.TApplicationException
+       if !errors.As(err, &aerr) || aerr.TypeId() != thrift.VALIDATION_FAILED {
+               t.Fatalf("expected VALIDATION_FAILED for an invalid key, got 
%v", err)
+       }
+}
+
+func TestStructKeyConst(t *testing.T) {
+       want := []thrift.MapEntry[*structkeytest.Key, int32]{
+               {Key: &structkeytest.Key{ID: 1, Name: "one"}, Value: 1},
+               {Key: &structkeytest.Key{ID: 2, Name: "two"}, Value: 2},
+       }
+       if len(structkeytest.STRUCT_KEYED_CONST) != len(want) {
+               t.Fatalf("got %d entries, want %d", 
len(structkeytest.STRUCT_KEYED_CONST), len(want))
+       }
+       for i, entry := range structkeytest.STRUCT_KEYED_CONST {
+               if !entry.Key.Equals(want[i].Key) || entry.Value != 
want[i].Value {
+                       t.Errorf("entry %d = {%v: %v}, want {%v: %v}", i, 
entry.Key, entry.Value, want[i].Key, want[i].Value)
+               }
+       }
+}

Review Comment:
   `TestStructKeyConst` assumes `STRUCT_KEYED_CONST` preserves a stable entry 
order and compares by index. `container_key_test.go` explicitly notes const map 
entries are emitted in compiler key order and tests them by key lookup, so this 
test is likely flaky across compiler/platform changes. Prefer validating the 
const entries as an unordered set (by key contents) rather than by position.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to