diff --git a/aptos-move/framework/aptos-stdlib/sources/comparator.move b/aptos-move/framework/aptos-stdlib/sources/comparator.move index f0a39c279467f..869b486b4ba5b 100644 --- a/aptos-move/framework/aptos-stdlib/sources/comparator.move +++ b/aptos-move/framework/aptos-stdlib/sources/comparator.move @@ -24,6 +24,9 @@ module aptos_std::comparator { } // Performs a comparison of two types after BCS serialization. + // BCS uses little endian encoding for all integer types, + // so comparison between primitive integer types will not behave as expected. + // For example, 1(0x1) will be larger than 256(0x100) after BCS serialization. public fun compare(left: &T, right: &T): Result { let left_bytes = bcs::to_bytes(left); let right_bytes = bcs::to_bytes(right); @@ -81,6 +84,20 @@ module aptos_std::comparator { assert!(is_greater_than(&compare(&value2, &value1)), 8); } + #[test] + #[expected_failure] + public fun test_integer() { + // 1(0x1) will be larger than 256(0x100) after BCS serialization. + let value0: u128 = 1; + let value1: u128 = 256; + + assert!(is_equal(&compare(&value0, &value0)), 0); + assert!(is_equal(&compare(&value1, &value1)), 1); + + assert!(is_smaller_than(&compare(&value0, &value1)), 2); + assert!(is_greater_than(&compare(&value1, &value0)), 3); + } + #[test] public fun test_u128() { let value0: u128 = 5;