Skip to content

Commit 5e42336

Browse files
authored
Sort Map by keys and then values (#16)
1 parent 9847bbe commit 5e42336

File tree

3 files changed

+28
-2
lines changed

3 files changed

+28
-2
lines changed

jamcodec/base.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,13 @@ def __eq__(self, other):
115115
return False
116116
return self.data == other.data
117117

118+
119+
def __lt__(self, other):
120+
return self.data < other.data
121+
122+
def __gt__(self, other):
123+
return self.data > other.data
124+
118125
def __len__(self):
119126
return len(self.data)
120127

jamcodec/types.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -977,8 +977,8 @@ def encode(self, value: Union[typing.Mapping, list]) -> JamBytes:
977977
# Convert to list
978978
value = value.items()
979979

980-
# Sort Map by keys
981-
value = sorted(value, key=lambda x: x[0])
980+
# Sort Map by keys and then values
981+
value = sorted(value)
982982

983983
# Encode length of Vec
984984
data = VarInt64.encode(len(value))

test/test_map.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,25 @@ def test_map_encode_list(self):
5656
data
5757
)
5858

59+
def test_map_encode_sort_key_values(self):
60+
obj = Map(U32, U32).new()
61+
value = [
62+
(2, 1),
63+
(2, 2),
64+
(1, 2),
65+
(1, 1)
66+
]
67+
68+
data = obj.encode(value)
69+
70+
self.assertEqual(
71+
JamBytes(
72+
"0x040100000001000000010000000200000002000000010000000200000002000000"
73+
),
74+
data
75+
)
76+
77+
5978
def test_map_decode(self):
6079
obj = Map(U32, Bytes).new()
6180

0 commit comments

Comments
 (0)