flatbuffers icon indicating copy to clipboard operation
flatbuffers copied to clipboard

[C#] Error Storing Dictionary : desgin scarlar type as the "key" field

Open liuxinjia opened this issue 3 years ago • 1 comments

It works fine when designing string filed as the "key" field. But problem happens when I use one of ushort field as the key .

[Fbs file] image

[TestCode] image

  • [C#, Windows, master]

liuxinjia avatar Jul 13 '22 15:07 liuxinjia

Can you share the generated code of CreateSortedVectorOfIntItem for both the string an ushort keys?

dbaileychess avatar Jul 26 '22 22:07 dbaileychess

The gen code of int key : image

The gen code of string key: image

Sorry for not replying in time😁 @dbaileychess

liuxinjia avatar Aug 01 '22 03:08 liuxinjia

It seems the String generated code is not correct, I'm not sure why it is comparing Ushort values when it should be comparing strings: https://github.com/google/flatbuffers/blob/8d1cc6ac7d9c750fef41f01012726a7d431be589/src/idl_gen_csharp.cpp#L625-L639

Could you give the schema for both the int and string keys? Perhaps name them something unique that won't clash with with types (Foo == string key and Bar == int key)

dbaileychess avatar Aug 06 '22 17:08 dbaileychess

Sorry for posting the wrong gen code for string keys.🤣 --the schema image

-- the gen code of CreateSortedVectorOfStrItem image

@dbaileychess But the problem occurs when I use ushort field as the key. Below is my complete test code.

-- the schema image

-- the Test code image

liuxinjia avatar Aug 08 '22 04:08 liuxinjia

It appears the issue is due to having a key == 0. If I set the keys to [1,2,3,4] everything works. Looking into this more.

dbaileychess avatar Aug 14 '22 05:08 dbaileychess

Ah, I remember this from the Java implementation, the default value for the IntItem.id is 0, and we don't push default values into the buffer unless 'ForceDefaults' is enabled. So when it is doing the binary search, it doesn't account for the default value and fails.

dbaileychess avatar Aug 14 '22 05:08 dbaileychess

This is leading to a bigger bug :( If you leave your code as is, and just change AddCount(fbb, i+1) it works. That's because, if any of the IntItem fields are non-default values, it will be written correctly to the buffer. However, if all the fields are defaulted, it isn't written to the buffer and the following fails:

 Assert.IsTrue(dict.Dict(0) != null);
Assert.IsTrue(dict.Dict(0).Value.Count == 0);

Which is a little scary, since the first Dict item should have a count of 0. But it is actually 1.

dbaileychess avatar Aug 14 '22 05:08 dbaileychess