Skip to content

Commit ff7e212

Browse files
hanslenarxbot
authored andcommitted
Fix negative numbers order
1 parent 8ad748e commit ff7e212

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

ciborium/src/value/integer.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,15 @@ impl Integer {
8585
(true, false) => {
8686
Ordering::Greater
8787
}
88+
(true, true) => {
89+
// For negative numbers the byte order puts numbers closer to 0 which
90+
// are lexically higher, lower. So -1 < -2 when sorting by be_bytes().
91+
match self.0.cmp(&other.0) {
92+
Ordering::Less => Ordering::Greater,
93+
Ordering::Equal => Ordering::Equal,
94+
Ordering::Greater => Ordering::Less,
95+
}
96+
}
8897
(_, _) => {
8998
self.0.cmp(&other.0)
9099
}

ciborium/tests/canonical.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,3 +58,31 @@ fn map() {
5858

5959
assert_eq!(hex::encode(&bytes1), "a80a002001f402186403617a048120056261610681186407");
6060
}
61+
62+
#[test]
63+
fn negative_numbers() {
64+
let mut array: Vec<CanonicalValue> = vec![
65+
cval!(10),
66+
cval!(-1),
67+
cval!(-2),
68+
cval!(-3),
69+
cval!(-4),
70+
cval!(false),
71+
cval!(100),
72+
cval!(-100),
73+
cval!(-200),
74+
cval!("z"),
75+
cval!([-1]),
76+
cval!(-300),
77+
cval!("aa"),
78+
cval!([100]),
79+
];
80+
let golden = array.clone();
81+
82+
// Shuffle the array.
83+
array.shuffle(&mut rand::thread_rng());
84+
85+
array.sort();
86+
87+
assert_eq!(array, golden);
88+
}

0 commit comments

Comments
 (0)