From 81411d8549a5313f71f4936dc80f6149d9e8841d Mon Sep 17 00:00:00 2001 From: Arjan Zijderveld <5286904+arjanz@users.noreply.github.com> Date: Wed, 15 Oct 2025 23:21:10 +0900 Subject: [PATCH] Sort Map by keys and then values --- jamcodec/base.py | 7 +++++++ jamcodec/types.py | 4 ++-- test/test_map.py | 19 +++++++++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/jamcodec/base.py b/jamcodec/base.py index 2bbaf9b..9a4cccb 100644 --- a/jamcodec/base.py +++ b/jamcodec/base.py @@ -115,6 +115,13 @@ def __eq__(self, other): return False return self.data == other.data + + def __lt__(self, other): + return self.data < other.data + + def __gt__(self, other): + return self.data > other.data + def __len__(self): return len(self.data) diff --git a/jamcodec/types.py b/jamcodec/types.py index 160e209..ce6cbda 100644 --- a/jamcodec/types.py +++ b/jamcodec/types.py @@ -977,8 +977,8 @@ def encode(self, value: Union[typing.Mapping, list]) -> JamBytes: # Convert to list value = value.items() - # Sort Map by keys - value = sorted(value, key=lambda x: x[0]) + # Sort Map by keys and then values + value = sorted(value) # Encode length of Vec data = VarInt64.encode(len(value)) diff --git a/test/test_map.py b/test/test_map.py index f6344a6..80bc915 100644 --- a/test/test_map.py +++ b/test/test_map.py @@ -56,6 +56,25 @@ def test_map_encode_list(self): data ) + def test_map_encode_sort_key_values(self): + obj = Map(U32, U32).new() + value = [ + (2, 1), + (2, 2), + (1, 2), + (1, 1) + ] + + data = obj.encode(value) + + self.assertEqual( + JamBytes( + "0x040100000001000000010000000200000002000000010000000200000002000000" + ), + data + ) + + def test_map_decode(self): obj = Map(U32, Bytes).new()