diff --git a/.tool-versions b/.tool-versions index e1290964..045dc3e7 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1 +1 @@ -scarb 2.6.4 +scarb 2.7.0 diff --git a/Scarb.toml b/Scarb.toml index 24d1b1b4..2332247f 100644 --- a/Scarb.toml +++ b/Scarb.toml @@ -17,10 +17,11 @@ name = "alexandria" version = "0.1.0" description = "Community maintained Cairo and Starknet libraries" homepage = "https://github.com/keep-starknet-strange/alexandria/" -cairo-version = "2.6.3" +cairo-version = "2.7.0" [workspace.dependencies] -starknet = "2.6.3" +starknet = "2.7.0" +cairo_test = "2.7.0" [workspace.tool.fmt] sort-module-level-items = true diff --git a/packages/ascii/Scarb.toml b/packages/ascii/Scarb.toml index 480e9ea9..d0a39062 100644 --- a/packages/ascii/Scarb.toml +++ b/packages/ascii/Scarb.toml @@ -9,4 +9,7 @@ edition = "2023_11" fmt.workspace = true [dependencies] -alexandria_data_structures = { path = "../data_structures" } \ No newline at end of file +alexandria_data_structures = { path = "../data_structures" } + +[dev-dependencies] +cairo_test.workspace = true \ No newline at end of file diff --git a/packages/ascii/src/integer.cairo b/packages/ascii/src/integer.cairo index 5554c2cc..1d7a0d40 100644 --- a/packages/ascii/src/integer.cairo +++ b/packages/ascii/src/integer.cairo @@ -37,15 +37,13 @@ impl ToAsciiArrayTraitImpl< } let mut num = self; - while num - .is_non_zero() { - let (quotient, remainder) = DivRem::div_rem( - num, - TryInto::::try_into(10).unwrap().try_into().expect('Division by 0') - ); - new_arr.append(remainder.into() + 48); - num = quotient; - }; + while num.is_non_zero() { + let (quotient, remainder) = DivRem::div_rem( + num, TryInto::::try_into(10).unwrap().try_into().expect('Division by 0') + ); + new_arr.append(remainder.into() + 48); + num = quotient; + }; new_arr } } @@ -110,8 +108,8 @@ impl BigIntegerToAsciiTraitImpl< match inverse_ascii_arr.pop_back() { Option::Some(val) => { let new_ascii = ascii * 256 + *val; - // if index is at 30 it means we have reached the max size of felt252 at 31 characters - // so we append the current ascii and reset the ascii to 0 + // if index is at 30 it means we have reached the max size of felt252 at 31 + // characters so we append the current ascii and reset the ascii to 0 ascii = if index == 30 { data.append(new_ascii); 0 @@ -175,22 +173,20 @@ impl U256ToAsciiTraitImpl of ToAsciiTrait> { let mut inverse_ascii_arr = self.to_inverse_ascii_array().span(); let mut index = 0; let mut ascii: felt252 = 0; - while let Option::Some(val) = inverse_ascii_arr - .pop_back() { - let new_ascii = ascii * 256 + *val; - // if index is currently at 30 it means we have processed the number for index 31 - // this means we have reached the max size of felt252 at 31 characters - // so we append the current ascii and reset the ascii to 0 - // do the same at index 61 as well because max u256 is 78 characters - ascii = - if index == 30 || index == 61 { - data.append(new_ascii); - 0 - } else { - new_ascii - }; - index += 1; + while let Option::Some(val) = inverse_ascii_arr.pop_back() { + let new_ascii = ascii * 256 + *val; + // if index is currently at 30 it means we have processed the number for index 31 + // this means we have reached the max size of felt252 at 31 characters + // so we append the current ascii and reset the ascii to 0 + // do the same at index 61 as well because max u256 is 78 characters + ascii = if index == 30 || index == 61 { + data.append(new_ascii); + 0 + } else { + new_ascii }; + index += 1; + }; if ascii.is_non_zero() { data.append(ascii); diff --git a/packages/ascii/src/tests/test_ascii_integer.cairo b/packages/ascii/src/tests/test_ascii_integer.cairo index a67f0db7..9ada074d 100644 --- a/packages/ascii/src/tests/test_ascii_integer.cairo +++ b/packages/ascii/src/tests/test_ascii_integer.cairo @@ -1,5 +1,5 @@ use alexandria_ascii::ToAsciiTrait; -use core::integer::BoundedInt; +use core::num::traits::Bounded; #[test] #[available_gas(2000000000)] @@ -7,28 +7,28 @@ fn u256_to_ascii() { // ------------------------------ max u256 test ----------------------------- // // max u256 int in cairo is GitHub Copilot: The maximum u256 number in Cairo is ` // 115792089237316195423570985008687907853269984665640564039457584007913129639935`. - let num: u256 = BoundedInt::max(); + let num: u256 = Bounded::MAX; let ascii: Array = num.to_ascii(); - assert_eq!(ascii.len(), 3, "max u256 wrong len"); - assert_eq!(*ascii.at(0), '1157920892373161954235709850086', "max u256 wrong first felt"); - assert_eq!(*ascii.at(1), '8790785326998466564056403945758', "max u256 wrong second felt"); - assert_eq!(*ascii.at(2), '4007913129639935', "max u256 wrong third felt"); + assert_eq!(ascii.len(), 3); + assert_eq!(*ascii.at(0), '1157920892373161954235709850086'); + assert_eq!(*ascii.at(1), '8790785326998466564056403945758'); + assert_eq!(*ascii.at(2), '4007913129639935'); // ------------------------------ min u256 test ----------------------------- // - let num: u256 = BoundedInt::min(); + let num: u256 = Bounded::MIN; let ascii: Array = num.to_ascii(); - assert_eq!(ascii.len(), 1, "min u256 wrong len"); - assert_eq!(*ascii.at(0), '0', "min u256 wrong felt"); + assert_eq!(ascii.len(), 1); + assert_eq!(*ascii.at(0), '0'); // ---------------------------- 31 char u256 test --------------------------- // let ascii: Array = 1157920892373161954235709850086_u256.to_ascii(); - assert_eq!(ascii.len(), 1, "u256 31 char wrong len"); - assert_eq!(*ascii.at(0), '1157920892373161954235709850086', "31 char u256 wrong felt"); + assert_eq!(ascii.len(), 1); + assert_eq!(*ascii.at(0), '1157920892373161954235709850086'); // ---------------------------- 62 char u256 test --------------------------- // let ascii: Array = 11579208923731619542357098500868790785326998466564056403945758_u256 .to_ascii(); - assert_eq!(ascii.len(), 2, "u256 31 char wrong len"); - assert_eq!(*ascii.at(0), '1157920892373161954235709850086', "31 char u256 wrong felt"); - assert_eq!(*ascii.at(1), '8790785326998466564056403945758', "62 char u256 wrong felt"); + assert_eq!(ascii.len(), 2); + assert_eq!(*ascii.at(0), '1157920892373161954235709850086'); + assert_eq!(*ascii.at(1), '8790785326998466564056403945758'); } #[test] @@ -36,64 +36,64 @@ fn u256_to_ascii() { fn u128_to_ascii() { // ------------------------------ max u128 test ----------------------------- // // max u128 int in cairo is 340282366920938463463374607431768211455 - let num: u128 = BoundedInt::max(); + let num: u128 = Bounded::MAX; let ascii: Array = num.to_ascii(); - assert_eq!(ascii.len(), 2, "max u128 wrong len"); - assert_eq!(*ascii.at(0), '3402823669209384634633746074317', "max u128 wrong first felt"); - assert_eq!(*ascii.at(1), '68211455', "max u128 wrong second felt"); + assert_eq!(ascii.len(), 2); + assert_eq!(*ascii.at(0), '3402823669209384634633746074317'); + assert_eq!(*ascii.at(1), '68211455'); // ------------------------------ min u128 test ----------------------------- // - let num: u128 = BoundedInt::min(); + let num: u128 = Bounded::MIN; let ascii: Array = num.to_ascii(); - assert_eq!(ascii.len(), 1, "min u128 wrong len"); - assert_eq!(*ascii.at(0), '0', "min u128 wrong felt"); + assert_eq!(ascii.len(), 1); + assert_eq!(*ascii.at(0), '0'); // ---------------------------- 31 char u128 test --------------------------- // let ascii: Array = 3402823669209384634633746074317_u128.to_ascii(); - assert_eq!(ascii.len(), 1, "u128 31 char wrong len"); - assert_eq!(*ascii.at(0), '3402823669209384634633746074317', "31 char u128 wrong felt"); + assert_eq!(ascii.len(), 1); + assert_eq!(*ascii.at(0), '3402823669209384634633746074317'); } #[test] #[available_gas(2000000)] fn u64_to_ascii() { // ------------------------------ max u64 test ------------------------------ // - let num: u64 = BoundedInt::max(); - assert_eq!(num.to_ascii(), '18446744073709551615', "incorrect u64 max felt"); + let num: u64 = Bounded::MAX; + assert_eq!(num.to_ascii(), '18446744073709551615'); // ------------------------------ min u64 test ------------------------------ // - let num: u64 = BoundedInt::min(); - assert_eq!(num.to_ascii(), '0', "incorrect u64 min felt"); + let num: u64 = Bounded::MIN; + assert_eq!(num.to_ascii(), '0'); } #[test] #[available_gas(2000000)] fn u32_to_ascii() { // ------------------------------ max u32 test ------------------------------ // - let num: u32 = BoundedInt::max(); - assert_eq!(num.to_ascii(), '4294967295', "incorrect u32 max felt"); + let num: u32 = Bounded::MAX; + assert_eq!(num.to_ascii(), '4294967295'); // ------------------------------ min u32 test ------------------------------ // - let num: u32 = BoundedInt::min(); - assert_eq!(num.to_ascii(), '0', "incorrect u32 min felt"); + let num: u32 = Bounded::MIN; + assert_eq!(num.to_ascii(), '0'); } #[test] #[available_gas(2000000)] fn u16_to_ascii() { // ------------------------------ max u16 test ------------------------------ // - let num: u16 = BoundedInt::max(); - assert_eq!(num.to_ascii(), '65535', "incorrect u16 max felt"); + let num: u16 = Bounded::MAX; + assert_eq!(num.to_ascii(), '65535'); // ------------------------------ min u16 test ------------------------------ // - let num: u16 = BoundedInt::min(); - assert_eq!(num.to_ascii(), '0', "incorrect u16 min felt"); + let num: u16 = Bounded::MIN; + assert_eq!(num.to_ascii(), '0'); } #[test] #[available_gas(2000000)] fn u8_to_ascii() { // ------------------------------- max u8 test ------------------------------ // - let num: u8 = BoundedInt::max(); - assert_eq!(num.to_ascii(), '255', "incorrect u8 max felt"); + let num: u8 = Bounded::MAX; + assert_eq!(num.to_ascii(), '255'); // ------------------------------- min u8 test ------------------------------ // - let num: u8 = BoundedInt::min(); - assert_eq!(num.to_ascii(), '0', "incorrect u8 min felt"); + let num: u8 = Bounded::MIN; + assert_eq!(num.to_ascii(), '0'); } diff --git a/packages/bytes/Scarb.toml b/packages/bytes/Scarb.toml index 5dcd1fb7..b10115b7 100644 --- a/packages/bytes/Scarb.toml +++ b/packages/bytes/Scarb.toml @@ -12,3 +12,6 @@ fmt.workspace = true alexandria_math = { path = "../math" } alexandria_data_structures = { path = "../data_structures" } starknet.workspace = true + +[dev-dependencies] +cairo_test.workspace = true diff --git a/packages/bytes/src/bytes.cairo b/packages/bytes/src/bytes.cairo index b8c5a4d3..b6dd5dcc 100644 --- a/packages/bytes/src/bytes.cairo +++ b/packages/bytes/src/bytes.cairo @@ -1,11 +1,12 @@ use alexandria_bytes::utils::{ - u128_join, read_sub_u128, u128_split, u128_array_slice, keccak_u128s_be, u8_array_to_u256 + u128_join, read_sub_u128, u128_split, u128_array_slice, keccak_u128s_be, u8_array_to_u256, + u32s_to_u256 }; -use alexandria_math::sha256::sha256; use alexandria_math::{U128BitShift, U256BitShift}; use core::byte_array::ByteArrayTrait; +use core::ops::index::IndexView; +use core::sha256; use starknet::ContractAddress; - /// Bytes is a dynamic array of u128, where each element contains 16 bytes. pub const BYTES_PER_ELEMENT: usize = 16; @@ -37,7 +38,8 @@ pub struct Bytes { data: Array } -pub impl BytesIndex of IndexView { +pub impl BytesIndex of IndexView { + type Target = @u128; fn index(self: @Bytes, index: usize) -> @u128 { self.data[index] } @@ -55,7 +57,7 @@ pub trait BytesTrait { fn locate(offset: usize) -> (usize, usize); /// Get Bytes size fn size(self: @Bytes) -> usize; - /// Get data + /// Get data fn data(self: Bytes) -> Array; /// update specific value (1 bytes) at specific offset fn update_at(ref self: Bytes, offset: usize, value: u8); @@ -116,8 +118,18 @@ pub trait BytesTrait { /// concat with other Bytes fn concat(ref self: Bytes, other: @Bytes); /// keccak hash + #[deprecated( + feature: "deprecated-keccak", + note: "Use `core::keccak::compute_keccak_byte_array`.", + since: "2.7.0" + )] fn keccak(self: @Bytes) -> u256; /// sha256 hash + #[deprecated( + feature: "deprecated-sha256", + note: "Use `core::sha256::compute_sha256_byte_array`.", + since: "2.7.0" + )] fn sha256(self: @Bytes) -> u256; } @@ -175,7 +187,7 @@ impl BytesImpl of BytesTrait { /// update specific value (1 bytes) at specific offset fn update_at(ref self: Bytes, offset: usize, value: u8) { assert(offset < self.size(), 'update out of bound'); - let mut new_bytes = BytesTrait::new_empty(); + let mut new_bytes = Self::new_empty(); // if update first bytes, ignore if offset > 0 { @@ -207,12 +219,12 @@ impl BytesImpl of BytesTrait { // check value in one element or two // if value in one element, just read it // if value in two elements, read them and join them - let (element_index, element_offset) = BytesTrait::locate(offset); + let (element_index, element_offset) = Self::locate(offset); let value_in_one_element = element_offset + size <= BYTES_PER_ELEMENT; let value = if value_in_one_element { read_sub_u128(*self.data[element_index], BYTES_PER_ELEMENT, element_offset, size) } else { - let (_, end_element_offset) = BytesTrait::locate(offset + size); + let (_, end_element_offset) = Self::locate(offset + size); let left = read_sub_u128( *self.data[element_index], BYTES_PER_ELEMENT, @@ -340,7 +352,7 @@ impl BytesImpl of BytesTrait { assert(offset + size <= self.size(), 'out of bound'); if size == 0 { - return (offset, BytesTrait::new_empty()); + return (offset, Self::new_empty()); } let mut array = array![]; @@ -367,7 +379,7 @@ impl BytesImpl of BytesTrait { offset = new_offset; } - return (offset, BytesTrait::new(size, array)); + return (offset, Self::new(size, array)); } /// read felt252 from Bytes @@ -409,7 +421,7 @@ impl BytesImpl of BytesTrait { assert(size <= 16, 'size must be less than 16'); let Bytes { size: old_bytes_size, mut data } = self; - let (last_data_index, last_element_size) = BytesTrait::locate(old_bytes_size); + let (last_data_index, last_element_size) = Self::locate(old_bytes_size); if last_element_size == 0 { let padded_value = u128_join(value, 0, BYTES_PER_ELEMENT - size); @@ -493,7 +505,7 @@ impl BytesImpl of BytesTrait { fn append_bytes31(ref self: Bytes, value: bytes31) { let mut value: u256 = value.into(); value = U256BitShift::shl(value, 8); - self.concat(@BytesTrait::new(31, array![value.high, value.low])); + self.concat(@Self::new(31, array![value.high, value.low])); } /// Write address into Bytes @@ -525,7 +537,7 @@ impl BytesImpl of BytesTrait { /// keccak hash fn keccak(self: @Bytes) -> u256 { - let (last_data_index, last_element_size) = BytesTrait::locate(self.size()); + let (last_data_index, last_element_size) = Self::locate(self.size()); if last_element_size == 0 { return keccak_u128s_be(self.data.span(), self.size()); } else { @@ -541,19 +553,18 @@ impl BytesImpl of BytesTrait { /// sha256 hash fn sha256(self: @Bytes) -> u256 { - let mut hash_data: Array = array![]; let mut i: usize = 0; let mut offset: usize = 0; - while i != self - .size() { - let (new_offset, hash_data_item) = self.read_u8(offset); - hash_data.append(hash_data_item); - offset = new_offset; - i += 1; - }; + let mut hash_data_byte_array = ""; + while i != self.size() { + let (new_offset, hash_data_item) = self.read_u8(offset); + hash_data_byte_array.append_byte(hash_data_item); + offset = new_offset; + i += 1; + }; - let output: Array = sha256(hash_data); - u8_array_to_u256(output.span()) + let output = sha256::compute_sha256_byte_array(@hash_data_byte_array); + u32s_to_u256(output.span()) } } @@ -573,18 +584,17 @@ pub impl BytesIntoByteArray of Into { fn into(self: Bytes) -> ByteArray { let mut res: ByteArray = Default::default(); let mut offset = 0; - while offset < self - .size() { - if offset + 31 <= self.size() { - let (new_offset, value) = self.read_bytes31(offset); - res.append_word(value.into(), 31); - offset = new_offset; - } else { - let (new_offset, value) = self.read_u8(offset); - res.append_byte(value); - offset = new_offset; - } - }; + while offset < self.size() { + if offset + 31 <= self.size() { + let (new_offset, value) = self.read_bytes31(offset); + res.append_word(value.into(), 31); + offset = new_offset; + } else { + let (new_offset, value) = self.read_u8(offset); + res.append_byte(value); + offset = new_offset; + } + }; res } } diff --git a/packages/bytes/src/storage.cairo b/packages/bytes/src/storage.cairo index 2b0bbf86..25fb3801 100644 --- a/packages/bytes/src/storage.cairo +++ b/packages/bytes/src/storage.cairo @@ -1,8 +1,9 @@ use alexandria_bytes::bytes::{Bytes, BytesTrait, BYTES_PER_ELEMENT}; +use core::num::traits::CheckedAdd; use starknet::SyscallResult; use starknet::storage_access::{ Store, StorageAddress, StorageBaseAddress, storage_address_from_base, - storage_base_address_from_felt252, storage_address_from_base_and_offset + storage_base_address_from_felt252, storage_address_from_base_and_offset, }; /// Store for a `Bytes` object. @@ -86,16 +87,15 @@ fn inner_read_bytes(address_domain: u32, address: StorageAddress) -> SyscallResu }; data.append(value); remaining_full_words -= 1; - index_in_chunk = match core::integer::u8_overflowing_add(index_in_chunk, 1) { - Result::Ok(x) => x, - Result::Err(_) => { - // After reading 256 `uint128`s `index_in_chunk` will overflow and we move to the - // next chunk. + + match index_in_chunk.checked_add(1) { + Option::Some(x) => { index_in_chunk = x; }, + Option::None => { chunk += 1; chunk_base = inner_bytes_pointer(address, chunk); - 0 + index_in_chunk = 0; }, - }; + } }?; if last_word_len != 0 { let last_word = starknet::syscalls::storage_read_syscall( @@ -131,16 +131,15 @@ fn inner_write_bytes( Result::Ok(_) => {}, Result::Err(err) => { break Result::Err(err); }, }; - index_in_chunk = match core::integer::u8_overflowing_add(index_in_chunk, 1) { - Result::Ok(x) => x, - Result::Err(_) => { - // After writing 256 `uint128`s `index_in_chunk` will overflow and we move to the - // next chunk. + + match index_in_chunk.checked_add(1) { + Option::Some(x) => { index_in_chunk = x; }, + Option::None => { chunk += 1; chunk_base = inner_bytes_pointer(address, chunk); - 0 + index_in_chunk = 0; }, - }; + } }?; Result::Ok(()) } diff --git a/packages/bytes/src/tests/test_bytes.cairo b/packages/bytes/src/tests/test_bytes.cairo index aca7edf9..b7146a5b 100644 --- a/packages/bytes/src/tests/test_bytes.cairo +++ b/packages/bytes/src/tests/test_bytes.cairo @@ -6,19 +6,19 @@ use starknet::ContractAddress; #[available_gas(20000000)] fn test_bytes_zero() { let bytes = BytesTrait::zero(1); - assert_eq!(bytes.size(), 1, "invalid size"); - assert_eq!(*bytes[0], 0, "invalid value"); + assert_eq!(bytes.size(), 1); + assert_eq!(*bytes[0], 0); let bytes = BytesTrait::zero(17); - assert_eq!(bytes.size(), 17, "invalid size"); - assert_eq!(*bytes[0], 0, "invalid value"); - assert_eq!(*bytes[1], 0, "invalid value"); + assert_eq!(bytes.size(), 17); + assert_eq!(*bytes[0], 0); + assert_eq!(*bytes[1], 0); let (_, value) = bytes.read_u8(15); - assert_eq!(value, 0, "invalid value"); + assert_eq!(value, 0); let (_, value) = bytes.read_u8(0); - assert_eq!(value, 0, "invalid value"); + assert_eq!(value, 0); let (_, value) = bytes.read_u8(16); - assert_eq!(value, 0, "invalid value"); + assert_eq!(value, 0); } #[test] @@ -35,24 +35,24 @@ fn test_bytes_update() { let mut bytes = BytesTrait::new(5, array![0x01020304050000000000000000000000]); bytes.update_at(0, 0x05); - assert_eq!(bytes.size(), 5, "update_size1"); - assert_eq!(*bytes[0], 0x05020304050000000000000000000000, "update_value_1"); + assert_eq!(bytes.size(), 5); + assert_eq!(*bytes[0], 0x05020304050000000000000000000000); bytes.update_at(1, 0x06); - assert_eq!(bytes.size(), 5, "update_size2"); - assert_eq!(*bytes[0], 0x05060304050000000000000000000000, "update_value_2"); + assert_eq!(bytes.size(), 5); + assert_eq!(*bytes[0], 0x05060304050000000000000000000000); bytes.update_at(2, 0x07); - assert_eq!(bytes.size(), 5, "update_size3"); - assert_eq!(*bytes[0], 0x05060704050000000000000000000000, "update_value_3"); + assert_eq!(bytes.size(), 5); + assert_eq!(*bytes[0], 0x05060704050000000000000000000000); bytes.update_at(3, 0x08); - assert_eq!(bytes.size(), 5, "update_size4"); - assert_eq!(*bytes[0], 0x05060708050000000000000000000000, "update_value_4"); + assert_eq!(bytes.size(), 5); + assert_eq!(*bytes[0], 0x05060708050000000000000000000000); bytes.update_at(4, 0x09); - assert_eq!(bytes.size(), 5, "update_size5"); - assert_eq!(*bytes[0], 0x05060708090000000000000000000000, "update_value_5"); + assert_eq!(bytes.size(), 5); + assert_eq!(*bytes[0], 0x05060708090000000000000000000000); let mut bytes = BytesTrait::new( 42, @@ -64,16 +64,16 @@ fn test_bytes_update() { ); bytes.update_at(16, 0x16); - assert_eq!(bytes.size(), 42, "update_size6"); - assert_eq!(*bytes[0], 0x01020304050607080910111213141516, "update_value_6"); - assert_eq!(*bytes[1], 0x16020304050607080910111213141516, "update_value_7"); - assert_eq!(*bytes[2], 0x01020304050607080910000000000000, "update_value_8"); + assert_eq!(bytes.size(), 42); + assert_eq!(*bytes[0], 0x01020304050607080910111213141516); + assert_eq!(*bytes[1], 0x16020304050607080910111213141516); + assert_eq!(*bytes[2], 0x01020304050607080910000000000000); bytes.update_at(15, 0x01); - assert_eq!(bytes.size(), 42, "update_size7"); - assert_eq!(*bytes[0], 0x01020304050607080910111213141501, "update_value_9"); - assert_eq!(*bytes[1], 0x16020304050607080910111213141516, "update_value_10"); - assert_eq!(*bytes[2], 0x01020304050607080910000000000000, "update_value_11"); + assert_eq!(bytes.size(), 42); + assert_eq!(*bytes[0], 0x01020304050607080910111213141501); + assert_eq!(*bytes[1], 0x16020304050607080910111213141516); + assert_eq!(*bytes[2], 0x01020304050607080910000000000000); } #[test] @@ -88,24 +88,24 @@ fn test_bytes_read_u128_packed() { let bytes = BytesTrait::new(42, array); let (new_offset, value) = bytes.read_u128_packed(0, 1); - assert_eq!(new_offset, 1, "read_u128_packed_1_offset"); - assert_eq!(value, 0x01, "read_u128_packed_1_value"); + assert_eq!(new_offset, 1); + assert_eq!(value, 0x01); let (new_offset, value) = bytes.read_u128_packed(new_offset, 14); - assert_eq!(new_offset, 15, "read_u128_packed_2_offset"); - assert_eq!(value, 0x0203040506070809101112131415, "read_u128_packed_2_value"); + assert_eq!(new_offset, 15); + assert_eq!(value, 0x0203040506070809101112131415); let (new_offset, value) = bytes.read_u128_packed(new_offset, 15); - assert_eq!(new_offset, 30, "read_u128_packed_3_offset"); - assert_eq!(value, 0x160102030405060708091011121314, "read_u128_packed_3_value"); + assert_eq!(new_offset, 30); + assert_eq!(value, 0x160102030405060708091011121314); let (new_offset, value) = bytes.read_u128_packed(new_offset, 8); - assert_eq!(new_offset, 38, "read_u128_packed_4_offset"); - assert_eq!(value, 0x1516010203040506, "read_u128_packed_4_value"); + assert_eq!(new_offset, 38); + assert_eq!(value, 0x1516010203040506); let (new_offset, value) = bytes.read_u128_packed(new_offset, 4); - assert_eq!(new_offset, 42, "read_u128_packed_5_offset"); - assert_eq!(value, 0x07080910, "read_u128_packed_5_value"); + assert_eq!(new_offset, 42); + assert_eq!(value, 0x07080910); } #[test] @@ -150,17 +150,17 @@ fn test_bytes_read_u128_array_packed() { let bytes = BytesTrait::new(42, array); let (new_offset, new_array) = bytes.read_u128_array_packed(0, 3, 3); - assert_eq!(new_offset, 9, "read_u128_array_1_offset"); - assert_eq!(*new_array[0], 0x010203, "read_u128_array_1_value_1"); - assert_eq!(*new_array[1], 0x040506, "read_u128_array_1_value_2"); - assert_eq!(*new_array[2], 0x070809, "read_u128_array_1_value_3"); + assert_eq!(new_offset, 9); + assert_eq!(*new_array[0], 0x010203); + assert_eq!(*new_array[1], 0x040506); + assert_eq!(*new_array[2], 0x070809); let (new_offset, new_array) = bytes.read_u128_array_packed(9, 4, 7); - assert_eq!(new_offset, 37, "read_u128_array_2_offset"); - assert_eq!(*new_array[0], 0x10111213141516, "read_u128_array_2_value_1"); - assert_eq!(*new_array[1], 0x01020304050607, "read_u128_array_2_value_2"); - assert_eq!(*new_array[2], 0x08091011121314, "read_u128_array_2_value_3"); - assert_eq!(*new_array[3], 0x15160102030405, "read_u128_array_2_value_4"); + assert_eq!(new_offset, 37); + assert_eq!(*new_array[0], 0x10111213141516); + assert_eq!(*new_array[1], 0x01020304050607); + assert_eq!(*new_array[2], 0x08091011121314); + assert_eq!(*new_array[3], 0x15160102030405); } #[test] @@ -205,8 +205,8 @@ fn test_bytes_read_felt252_packed() { let bytes = BytesTrait::new(42, array); let (new_offset, value) = bytes.read_felt252_packed(13, 20); - assert_eq!(new_offset, 33, "read_felt252_1_offset"); - assert_eq!(value, 0x1415160102030405060708091011121314151601, "read_felt252_1_value"); + assert_eq!(new_offset, 33); + assert_eq!(value, 0x1415160102030405060708091011121314151601); } #[test] @@ -251,8 +251,8 @@ fn test_bytes_read_u8() { let bytes = BytesTrait::new(42, array); let (new_offset, value) = bytes.read_u8(15); - assert_eq!(new_offset, 16, "read_u8_offset"); - assert_eq!(value, 0x16, "read_u8_value"); + assert_eq!(new_offset, 16); + assert_eq!(value, 0x16); } #[test] @@ -267,8 +267,8 @@ fn test_bytes_read_u16() { let bytes = BytesTrait::new(42, array); let (new_offset, value) = bytes.read_u16(15); - assert_eq!(new_offset, 17, "read_u16_offset"); - assert_eq!(value, 0x1601, "read_u16_value"); + assert_eq!(new_offset, 17); + assert_eq!(value, 0x1601); } #[test] @@ -283,8 +283,8 @@ fn test_bytes_read_u32() { let bytes = BytesTrait::new(42, array); let (new_offset, value) = bytes.read_u32(15); - assert_eq!(new_offset, 19, "read_u32_offset"); - assert_eq!(value, 0x16010203, "read_u32_value"); + assert_eq!(new_offset, 19); + assert_eq!(value, 0x16010203); } #[test] @@ -299,8 +299,8 @@ fn test_bytes_read_usize() { let bytes = BytesTrait::new(42, array); let (new_offset, value) = bytes.read_usize(15); - assert_eq!(new_offset, 19, "read_usize_offset"); - assert_eq!(value, 0x16010203, "read_usize_value"); + assert_eq!(new_offset, 19); + assert_eq!(value, 0x16010203); } #[test] @@ -315,8 +315,8 @@ fn test_bytes_read_u64() { let bytes = BytesTrait::new(42, array); let (new_offset, value) = bytes.read_u64(15); - assert_eq!(new_offset, 23, "read_u64_offset"); - assert_eq!(value, 0x1601020304050607, "read_u64_value"); + assert_eq!(new_offset, 23); + assert_eq!(value, 0x1601020304050607); } #[test] @@ -331,8 +331,8 @@ fn test_bytes_read_u128() { let bytes = BytesTrait::new(42, array); let (new_offset, value) = bytes.read_u128(15); - assert_eq!(new_offset, 31, "read_u128_offset"); - assert_eq!(value, 0x16010203040506070809101112131415, "read_u128_value"); + assert_eq!(new_offset, 31); + assert_eq!(value, 0x16010203040506070809101112131415); } #[test] @@ -347,9 +347,9 @@ fn test_bytes_read_u256() { let bytes = BytesTrait::new(42, array); let (new_offset, value) = bytes.read_u256(4); - assert_eq!(new_offset, 36, "read_u256_1_offset"); - assert_eq!(value.high, 0x05060708091011121314151601020304, "read_u256_1_value_high"); - assert_eq!(value.low, 0x05060708091011121314151601020304, "read_u256_1_value_low"); + assert_eq!(new_offset, 36); + assert_eq!(value.high, 0x05060708091011121314151601020304); + assert_eq!(value.low, 0x05060708091011121314151601020304); } #[test] @@ -359,7 +359,7 @@ fn test_bytes_read_bytes31() { 31, array![0x0102030405060708090a0b0c0d0e0f10, 0x1112131415161718191a1b1c1d1e1f00] ); let (offset, val) = bytes.read_bytes31(0); - assert_eq!(offset, 31, "Offset after read_bytes31 failed"); + assert_eq!(offset, 31); let byte31: bytes31 = 0x0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f .try_into() .unwrap(); @@ -381,13 +381,13 @@ fn test_bytes_read_u256_array() { let bytes = BytesTrait::new(88, array); let (new_offset, new_array) = bytes.read_u256_array(7, 2); - assert_eq!(new_offset, 71, "read_u256_array_offset"); + assert_eq!(new_offset, 71); let result: u256 = *new_array[0]; - assert_eq!(result.high, 0x08091011121314151616151413121110, "read_256_array_value_1_high"); - assert_eq!(result.low, 0x09080706050403020116151413121110, "read_256_array_value_1_low"); + assert_eq!(result.high, 0x08091011121314151616151413121110); + assert_eq!(result.low, 0x09080706050403020116151413121110); let result: u256 = *new_array[1]; - assert_eq!(result.high, 0x09080706050403020101020304050607, "read_256_array_value_2_high"); - assert_eq!(result.low, 0x08091011121314151601020304050607, "read_256_array_value_2_low"); + assert_eq!(result.high, 0x09080706050403020101020304050607); + assert_eq!(result.low, 0x08091011121314151601020304050607); } #[test] @@ -403,8 +403,8 @@ fn test_bytes_read_address() { let address = 0x015401855d7796176b05d160196ff92381eb7910f5446c2e0e04e13db2194a4f; let (new_offset, value) = bytes.read_address(14); - assert_eq!(new_offset, 46, "read_address_offset"); - assert_eq!(value.into(), address, "read_address_value"); + assert_eq!(new_offset, 46); + assert_eq!(value.into(), address); } #[test] @@ -420,31 +420,31 @@ fn test_bytes_read_bytes() { let (new_offset, sub_bytes) = bytes.read_bytes(4, 37); let sub_bytes_data = @sub_bytes; - assert_eq!(new_offset, 41, "read_bytes_offset"); - assert_eq!(sub_bytes.size(), 37, "read_bytes_size"); - assert_eq!(*sub_bytes_data[0], 0x05060708091011121314015401855d77, "read_bytes_value_1"); - assert_eq!(*sub_bytes_data[1], 0x96176b05d160196ff92381eb7910f544, "read_bytes_value_2"); - assert_eq!(*sub_bytes_data[2], 0x6c2e0e04e10000000000000000000000, "read_bytes_value_3"); + assert_eq!(new_offset, 41); + assert_eq!(sub_bytes.size(), 37); + assert_eq!(*sub_bytes_data[0], 0x05060708091011121314015401855d77); + assert_eq!(*sub_bytes_data[1], 0x96176b05d160196ff92381eb7910f544); + assert_eq!(*sub_bytes_data[2], 0x6c2e0e04e10000000000000000000000); let (new_offset, sub_bytes) = bytes.read_bytes(0, 14); let sub_bytes_data = @sub_bytes; - assert_eq!(new_offset, 14, "read_bytes_offset"); - assert_eq!(sub_bytes.size(), 14, "read_bytes_size"); - assert_eq!(*sub_bytes_data[0], 0x01020304050607080910111213140000, "read_bytes_value_4"); + assert_eq!(new_offset, 14); + assert_eq!(sub_bytes.size(), 14); + assert_eq!(*sub_bytes_data[0], 0x01020304050607080910111213140000); // read first byte let (new_offset, sub_bytes) = bytes.read_bytes(0, 1); let sub_bytes_data = @sub_bytes; - assert_eq!(new_offset, 1, "read_bytes_offset"); - assert_eq!(sub_bytes.size(), 1, "read_bytes_size"); - assert_eq!(*sub_bytes_data[0], 0x01000000000000000000000000000000, "read_bytes_value_5"); + assert_eq!(new_offset, 1); + assert_eq!(sub_bytes.size(), 1); + assert_eq!(*sub_bytes_data[0], 0x01000000000000000000000000000000); // read last byte let (new_offset, sub_bytes) = bytes.read_bytes(45, 1); let sub_bytes_data = @sub_bytes; - assert_eq!(new_offset, 46, "read_bytes_offset"); - assert_eq!(sub_bytes.size(), 1, "read_bytes_size"); - assert_eq!(*sub_bytes_data[0], 0x4f000000000000000000000000000000, "read_bytes_value_6"); + assert_eq!(new_offset, 46); + assert_eq!(sub_bytes.size(), 1); + assert_eq!(*sub_bytes_data[0], 0x4f000000000000000000000000000000); } #[test] @@ -454,70 +454,70 @@ fn test_bytes_append() { // append_u128_packed bytes.append_u128_packed(0x101112131415161718, 9); - assert_eq!(bytes.size(), 9, "append_u128_packed_1_size"); - assert_eq!(*bytes[0], 0x10111213141516171800000000000000, "append_u128_packed_1_value_1"); + assert_eq!(bytes.size(), 9); + assert_eq!(*bytes[0], 0x10111213141516171800000000000000); bytes = BytesTrait::new(bytes.size(), bytes.data()); bytes.append_u128_packed(0x101112131415161718, 9); - assert_eq!(bytes.size(), 18, "append_u128_packed_2_size"); - assert_eq!(*bytes[0], 0x10111213141516171810111213141516, "append_u128_packed_2_value_1"); - assert_eq!(*bytes[1], 0x17180000000000000000000000000000, "append_u128_packed_2_value_2"); + assert_eq!(bytes.size(), 18); + assert_eq!(*bytes[0], 0x10111213141516171810111213141516); + assert_eq!(*bytes[1], 0x17180000000000000000000000000000); bytes = BytesTrait::new(bytes.size(), bytes.data()); // append_u8 bytes.append_u8(0x01); - assert_eq!(bytes.size(), 19, "append_u8_size"); - assert_eq!(*bytes[0], 0x10111213141516171810111213141516, "append_u8_value_1"); - assert_eq!(*bytes[1], 0x17180100000000000000000000000000, "append_u8_value_2"); + assert_eq!(bytes.size(), 19); + assert_eq!(*bytes[0], 0x10111213141516171810111213141516); + assert_eq!(*bytes[1], 0x17180100000000000000000000000000); bytes = BytesTrait::new(bytes.size(), bytes.data()); // append_u16 bytes.append_u16(0x0102); - assert_eq!(bytes.size(), 21, "append_u16_size"); - assert_eq!(*bytes[0], 0x10111213141516171810111213141516, "append_u16_value_1"); - assert_eq!(*bytes[1], 0x17180101020000000000000000000000, "append_u16_value_2"); + assert_eq!(bytes.size(), 21); + assert_eq!(*bytes[0], 0x10111213141516171810111213141516); + assert_eq!(*bytes[1], 0x17180101020000000000000000000000); bytes = BytesTrait::new(bytes.size(), bytes.data()); // append_u32 bytes.append_u32(0x01020304); - assert_eq!(bytes.size(), 25, "append_u32_size"); - assert_eq!(*bytes[0], 0x10111213141516171810111213141516, "append_u32_value_1"); - assert_eq!(*bytes[1], 0x17180101020102030400000000000000, "append_u32_value_2"); + assert_eq!(bytes.size(), 25); + assert_eq!(*bytes[0], 0x10111213141516171810111213141516); + assert_eq!(*bytes[1], 0x17180101020102030400000000000000); bytes = BytesTrait::new(bytes.size(), bytes.data()); // append_usize bytes.append_usize(0x01); - assert_eq!(bytes.size(), 29, "append_usize_size"); - assert_eq!(*bytes[0], 0x10111213141516171810111213141516, "append_usize_value_1"); - assert_eq!(*bytes[1], 0x17180101020102030400000001000000, "append_usize_value_2"); + assert_eq!(bytes.size(), 29); + assert_eq!(*bytes[0], 0x10111213141516171810111213141516); + assert_eq!(*bytes[1], 0x17180101020102030400000001000000); bytes = BytesTrait::new(bytes.size(), bytes.data()); // append_u64 bytes.append_u64(0x030405060708); - assert_eq!(bytes.size(), 37, "append_u64_size"); - assert_eq!(*bytes[0], 0x10111213141516171810111213141516, "append_u64_value_1"); - assert_eq!(*bytes[1], 0x17180101020102030400000001000003, "append_u64_value_2"); - assert_eq!(*bytes[2], 0x04050607080000000000000000000000, "append_u64_value_3"); + assert_eq!(bytes.size(), 37); + assert_eq!(*bytes[0], 0x10111213141516171810111213141516); + assert_eq!(*bytes[1], 0x17180101020102030400000001000003); + assert_eq!(*bytes[2], 0x04050607080000000000000000000000); bytes = BytesTrait::new(bytes.size(), bytes.data()); // append_u128 bytes.append_u128(0x101112131415161718); - assert_eq!(bytes.size(), 53, "append_u128_size"); - assert_eq!(*bytes[0], 0x10111213141516171810111213141516, "append_u128_value_1"); - assert_eq!(*bytes[1], 0x17180101020102030400000001000003, "append_u128_value_2"); - assert_eq!(*bytes[2], 0x04050607080000000000000010111213, "append_u128_value_3"); - assert_eq!(*bytes[3], 0x14151617180000000000000000000000, "append_u128_value_4"); + assert_eq!(bytes.size(), 53); + assert_eq!(*bytes[0], 0x10111213141516171810111213141516); + assert_eq!(*bytes[1], 0x17180101020102030400000001000003); + assert_eq!(*bytes[2], 0x04050607080000000000000010111213); + assert_eq!(*bytes[3], 0x14151617180000000000000000000000); bytes = BytesTrait::new(bytes.size(), bytes.data()); // append_u256 bytes.append_u256(u256 { low: 0x01020304050607, high: 0x010203040506070809 }); - assert_eq!(bytes.size(), 85, "append_u256_size"); - assert_eq!(*bytes[0], 0x10111213141516171810111213141516, "append_u256_value_1"); - assert_eq!(*bytes[1], 0x17180101020102030400000001000003, "append_u256_value_2"); - assert_eq!(*bytes[2], 0x04050607080000000000000010111213, "append_u256_value_3"); - assert_eq!(*bytes[3], 0x14151617180000000000000001020304, "append_u256_value_4"); - assert_eq!(*bytes[4], 0x05060708090000000000000000000102, "append_u256_value_5"); - assert_eq!(*bytes[5], 0x03040506070000000000000000000000, "append_u256_value_6"); + assert_eq!(bytes.size(), 85); + assert_eq!(*bytes[0], 0x10111213141516171810111213141516); + assert_eq!(*bytes[1], 0x17180101020102030400000001000003); + assert_eq!(*bytes[2], 0x04050607080000000000000010111213); + assert_eq!(*bytes[3], 0x14151617180000000000000001020304); + assert_eq!(*bytes[4], 0x05060708090000000000000000000102); + assert_eq!(*bytes[5], 0x03040506070000000000000000000000); bytes = BytesTrait::new(bytes.size(), bytes.data()); // append_address @@ -525,15 +525,15 @@ fn test_bytes_append() { .try_into() .unwrap(); bytes.append_address(address); - assert_eq!(bytes.size(), 117, "append_address_size"); - assert_eq!(*bytes[0], 0x10111213141516171810111213141516, "append_address_value_1"); - assert_eq!(*bytes[1], 0x17180101020102030400000001000003, "append_address_value_2"); - assert_eq!(*bytes[2], 0x04050607080000000000000010111213, "append_address_value_3"); - assert_eq!(*bytes[3], 0x14151617180000000000000001020304, "append_address_value_4"); - assert_eq!(*bytes[4], 0x05060708090000000000000000000102, "append_address_value_5"); - assert_eq!(*bytes[5], 0x0304050607015401855d7796176b05d1, "append_address_value_6"); - assert_eq!(*bytes[6], 0x60196ff92381eb7910f5446c2e0e04e1, "append_address_value_7"); - assert_eq!(*bytes[7], 0x3db2194a4f0000000000000000000000, "append_address_value_8"); + assert_eq!(bytes.size(), 117); + assert_eq!(*bytes[0], 0x10111213141516171810111213141516); + assert_eq!(*bytes[1], 0x17180101020102030400000001000003); + assert_eq!(*bytes[2], 0x04050607080000000000000010111213); + assert_eq!(*bytes[3], 0x14151617180000000000000001020304); + assert_eq!(*bytes[4], 0x05060708090000000000000000000102); + assert_eq!(*bytes[5], 0x0304050607015401855d7796176b05d1); + assert_eq!(*bytes[6], 0x60196ff92381eb7910f5446c2e0e04e1); + assert_eq!(*bytes[7], 0x3db2194a4f0000000000000000000000); } #[test] @@ -559,53 +559,53 @@ fn test_bytes_concat() { let other = BytesTrait::new(46, array); bytes.concat(@other); - assert_eq!(bytes.size(), 163, "concat_size"); - assert_eq!(*bytes[0], 0x10111213141516171810111213141516, "concat_value_1"); - assert_eq!(*bytes[1], 0x17180101020102030400000001000003, "concat_value_2"); - assert_eq!(*bytes[2], 0x04050607080000000000000010111213, "concat_value_3"); - assert_eq!(*bytes[3], 0x14151617180000000000000001020304, "concat_value_4"); - assert_eq!(*bytes[4], 0x05060708090000000000000000000102, "concat_value_5"); - assert_eq!(*bytes[5], 0x0304050607015401855d7796176b05d1, "concat_value_6"); - assert_eq!(*bytes[6], 0x60196ff92381eb7910f5446c2e0e04e1, "concat_value_7"); - assert_eq!(*bytes[7], 0x3db2194a4f0102030405060708091011, "concat_value_8"); - assert_eq!(*bytes[8], 0x121314015401855d7796176b05d16019, "concat_value_9"); - assert_eq!(*bytes[9], 0x6ff92381eb7910f5446c2e0e04e13db2, "concat_value_10"); - assert_eq!(*bytes[10], 0x194a4f00000000000000000000000000, "concat_value_11"); + assert_eq!(bytes.size(), 163); + assert_eq!(*bytes[0], 0x10111213141516171810111213141516); + assert_eq!(*bytes[1], 0x17180101020102030400000001000003); + assert_eq!(*bytes[2], 0x04050607080000000000000010111213); + assert_eq!(*bytes[3], 0x14151617180000000000000001020304); + assert_eq!(*bytes[4], 0x05060708090000000000000000000102); + assert_eq!(*bytes[5], 0x0304050607015401855d7796176b05d1); + assert_eq!(*bytes[6], 0x60196ff92381eb7910f5446c2e0e04e1); + assert_eq!(*bytes[7], 0x3db2194a4f0102030405060708091011); + assert_eq!(*bytes[8], 0x121314015401855d7796176b05d16019); + assert_eq!(*bytes[9], 0x6ff92381eb7910f5446c2e0e04e13db2); + assert_eq!(*bytes[10], 0x194a4f00000000000000000000000000); bytes = BytesTrait::new(bytes.size(), bytes.data()); // empty bytes concat let mut empty_bytes = BytesTrait::new_empty(); empty_bytes.concat(@bytes); - assert_eq!(bytes.size(), 163, "concat_size"); - assert_eq!(*bytes[0], 0x10111213141516171810111213141516, "concat_value_1"); - assert_eq!(*bytes[1], 0x17180101020102030400000001000003, "concat_value_2"); - assert_eq!(*bytes[2], 0x04050607080000000000000010111213, "concat_value_3"); - assert_eq!(*bytes[3], 0x14151617180000000000000001020304, "concat_value_4"); - assert_eq!(*bytes[4], 0x05060708090000000000000000000102, "concat_value_5"); - assert_eq!(*bytes[5], 0x0304050607015401855d7796176b05d1, "concat_value_6"); - assert_eq!(*bytes[6], 0x60196ff92381eb7910f5446c2e0e04e1, "concat_value_7"); - assert_eq!(*bytes[7], 0x3db2194a4f0102030405060708091011, "concat_value_8"); - assert_eq!(*bytes[8], 0x121314015401855d7796176b05d16019, "concat_value_9"); - assert_eq!(*bytes[9], 0x6ff92381eb7910f5446c2e0e04e13db2, "concat_value_10"); - assert_eq!(*bytes[10], 0x194a4f00000000000000000000000000, "concat_value_11"); + assert_eq!(bytes.size(), 163); + assert_eq!(*bytes[0], 0x10111213141516171810111213141516); + assert_eq!(*bytes[1], 0x17180101020102030400000001000003); + assert_eq!(*bytes[2], 0x04050607080000000000000010111213); + assert_eq!(*bytes[3], 0x14151617180000000000000001020304); + assert_eq!(*bytes[4], 0x05060708090000000000000000000102); + assert_eq!(*bytes[5], 0x0304050607015401855d7796176b05d1); + assert_eq!(*bytes[6], 0x60196ff92381eb7910f5446c2e0e04e1); + assert_eq!(*bytes[7], 0x3db2194a4f0102030405060708091011); + assert_eq!(*bytes[8], 0x121314015401855d7796176b05d16019); + assert_eq!(*bytes[9], 0x6ff92381eb7910f5446c2e0e04e13db2); + assert_eq!(*bytes[10], 0x194a4f00000000000000000000000000); // concat empty_bytes let empty_bytes = BytesTrait::new_empty(); bytes.concat(@empty_bytes); - assert_eq!(bytes.size(), 163, "concat_size"); - assert_eq!(*bytes[0], 0x10111213141516171810111213141516, "concat_value_1"); - assert_eq!(*bytes[1], 0x17180101020102030400000001000003, "concat_value_2"); - assert_eq!(*bytes[2], 0x04050607080000000000000010111213, "concat_value_3"); - assert_eq!(*bytes[3], 0x14151617180000000000000001020304, "concat_value_4"); - assert_eq!(*bytes[4], 0x05060708090000000000000000000102, "concat_value_5"); - assert_eq!(*bytes[5], 0x0304050607015401855d7796176b05d1, "concat_value_6"); - assert_eq!(*bytes[6], 0x60196ff92381eb7910f5446c2e0e04e1, "concat_value_7"); - assert_eq!(*bytes[7], 0x3db2194a4f0102030405060708091011, "concat_value_8"); - assert_eq!(*bytes[8], 0x121314015401855d7796176b05d16019, "concat_value_9"); - assert_eq!(*bytes[9], 0x6ff92381eb7910f5446c2e0e04e13db2, "concat_value_10"); - assert_eq!(*bytes[10], 0x194a4f00000000000000000000000000, "concat_value_11"); + assert_eq!(bytes.size(), 163); + assert_eq!(*bytes[0], 0x10111213141516171810111213141516); + assert_eq!(*bytes[1], 0x17180101020102030400000001000003); + assert_eq!(*bytes[2], 0x04050607080000000000000010111213); + assert_eq!(*bytes[3], 0x14151617180000000000000001020304); + assert_eq!(*bytes[4], 0x05060708090000000000000000000102); + assert_eq!(*bytes[5], 0x0304050607015401855d7796176b05d1); + assert_eq!(*bytes[6], 0x60196ff92381eb7910f5446c2e0e04e1); + assert_eq!(*bytes[7], 0x3db2194a4f0102030405060708091011); + assert_eq!(*bytes[8], 0x121314015401855d7796176b05d16019); + assert_eq!(*bytes[9], 0x6ff92381eb7910f5446c2e0e04e13db2); + assert_eq!(*bytes[10], 0x194a4f00000000000000000000000000); } #[test] @@ -621,7 +621,7 @@ fn test_bytes_keccak() { let bytes = BytesTrait::new_empty(); let hash: u256 = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; let res = bytes.keccak(); - assert_eq!(res, hash, "bytes_keccak_0"); + assert_eq!(res, hash); // u256{low: 1, high: 0} let mut array = array![]; @@ -630,7 +630,7 @@ fn test_bytes_keccak() { let bytes: Bytes = BytesTrait::new(32, array); let res = bytes.keccak(); let hash: u256 = 0xb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6; - assert_eq!(res, hash, "bytes_keccak_1"); + assert_eq!(res, hash); // test_bytes_append bytes let mut array = array![]; @@ -647,7 +647,7 @@ fn test_bytes_keccak() { let hash: u256 = 0xcb1bcb5098bb2f588b82ea341e3b1148b7d1eeea2552d624b30f4240b5b85995; let res = bytes.keccak(); - assert_eq!(res, hash, "bytes_keccak_2"); + assert_eq!(res, hash); } #[test] @@ -657,7 +657,7 @@ fn test_bytes_sha256() { let bytes = BytesTrait::new_empty(); let hash: u256 = 0xe3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855; let res = bytes.sha256(); - assert_eq!(res, hash, "bytes_sha256_0"); + assert_eq!(res, hash); // u256{low: 1, high: 0} // 0x0000000000000000000000000000000000000000000000000000000000000001 @@ -665,7 +665,7 @@ fn test_bytes_sha256() { let bytes: Bytes = BytesTrait::new(32, array); let res = bytes.sha256(); let hash: u256 = 0xec4916dd28fc4c10d78e287ca5d9cc51ee1ae73cbfde08c6b37324cbfaac8bc5; - assert_eq!(res, hash, "bytes_sha256_1"); + assert_eq!(res, hash); // test_bytes_append bytes let array = array![ @@ -683,7 +683,7 @@ fn test_bytes_sha256() { let hash: u256 = 0xc3ab2c0ce2c246454f265f531ab14f210215ce72b91c23338405c273dc14ce1d; let res = bytes.sha256(); - assert_eq!(res, hash, "bytes_sha256_2"); + assert_eq!(res, hash); } #[test] @@ -699,5 +699,5 @@ fn test_byte_array_conversions() { ); let byte_array: ByteArray = bytes.clone().into(); let new_bytes: Bytes = byte_array.into(); - assert_eq!(bytes, new_bytes, "byte <-> byte_array conversion failed"); + assert_eq!(bytes, new_bytes); } diff --git a/packages/bytes/src/tests/test_bytes_store.cairo b/packages/bytes/src/tests/test_bytes_store.cairo index fa40c9ef..b4eca5c6 100644 --- a/packages/bytes/src/tests/test_bytes_store.cairo +++ b/packages/bytes/src/tests/test_bytes_store.cairo @@ -45,7 +45,7 @@ mod tests { #[test] fn test_deploy() { let contract = deploy(); - assert_eq!(contract.get_bytes(), BytesTrait::new_empty(), "Initial bytes should be empty"); + assert_eq!(contract.get_bytes(), BytesTrait::new_empty()); } #[test] @@ -53,7 +53,7 @@ mod tests { let contract = deploy(); let bytes = BytesTrait::new(32, array![0x01020304050607080910, 0x11121314151617181920]); contract.set_bytes(bytes.clone()); - assert_eq!(contract.get_bytes(), bytes, "Bytes should be set correctly"); + assert_eq!(contract.get_bytes(), bytes); } #[test] @@ -66,6 +66,6 @@ mod tests { ] ); contract.set_bytes(bytes.clone()); - assert_eq!(contract.get_bytes(), bytes, "Bytes should be set correctly"); + assert_eq!(contract.get_bytes(), bytes); } } diff --git a/packages/bytes/src/utils.cairo b/packages/bytes/src/utils.cairo index cc77502b..0283fe68 100644 --- a/packages/bytes/src/utils.cairo +++ b/packages/bytes/src/utils.cairo @@ -21,15 +21,14 @@ pub impl BytesDebug of Debug { let prefix: ByteArray = "0x"; Display::fmt(@prefix, ref f)?; let mut res: Result<(), Error> = Result::Ok(()); - while i < self - .size() { - let (new_i, value) = self.read_u8(i); - res = format_byte_hex(value, ref f); - if res.is_err() { - break; - } - i = new_i; - }; + while i < self.size() { + let (new_i, value) = self.read_u8(i); + res = format_byte_hex(value, ref f); + if res.is_err() { + break; + } + i = new_i; + }; res } } @@ -40,15 +39,14 @@ pub impl BytesDisplay of Display { let prefix: ByteArray = "0x"; Display::fmt(@prefix, ref f)?; let mut res: Result<(), Error> = Result::Ok(()); - while i < self - .size() { - let (new_i, value) = self.read_u8(i); - res = format_byte_hex(value, ref f); - if res.is_err() { - break; - } - i = new_i; - }; + while i < self.size() { + let (new_i, value) = self.read_u8(i); + res = format_byte_hex(value, ref f); + if res.is_err() { + break; + } + i = new_i; + }; res } } @@ -56,15 +54,14 @@ pub impl BytesDisplay of Display { /// Computes the keccak256 of multiple uint128 values. /// The values are interpreted as big-endian. /// https://github.com/starkware-libs/cairo/blob/main/corelib/src/keccak.cairo -pub fn keccak_u128s_be(mut input: Span, n_bytes: usize) -> u256 { +pub fn keccak_u128s_be(input: Span, n_bytes: usize) -> u256 { let mut keccak_input = array![]; let mut size = n_bytes; - while let Option::Some(v) = input - .pop_front() { - let value_size = uint_min(size, 16); - keccak_add_uint128_be(ref keccak_input, *v, value_size); - size -= value_size; - }; + for v in input { + let value_size = core::cmp::min(size, 16); + keccak_add_uint128_be(ref keccak_input, *v, value_size); + size -= value_size; + }; let aligned = n_bytes % 8 == 0; if aligned { @@ -77,16 +74,6 @@ pub fn keccak_u128s_be(mut input: Span, n_bytes: usize) -> u256 { } } -/// return the minimal value -/// support u8, u16, u32, u64, u128, u256 -fn uint_min, +PartialOrd, +Copy>(l: T, r: T) -> T { - if l <= r { - l - } else { - r - } -} - fn u256_reverse_endian(input: u256) -> u256 { let low = u128_byte_reverse(input.high); let high = u128_byte_reverse(input.low); @@ -120,15 +107,14 @@ fn update_u256_array_at(arr: @Array, index: usize, value: u256) -> Array) -> u256 { u256 { low, high } } +pub fn u32s_to_u256(arr: Span) -> u256 { + assert!(arr.len() == 8, "u32s_to_u2562: input must be 8 elements long"); + let low: u128 = (*arr[7]).into() + + (*arr[6]).into() * 0x1_0000_0000 + + (*arr[5]).into() * 0x1_0000_0000_0000_0000 + + (*arr[4]).into() * 0x1_0000_0000_0000_0000_0000_0000; + let low = low.try_into().expect('u32s_to_u2562:overflow-low'); + let high = (*arr[3]).into() + + (*arr[2]).into() * 0x1_0000_0000 + + (*arr[1]).into() * 0x1_0000_0000_0000_0000 + + (*arr[0]).into() * 0x1_0000_0000_0000_0000_0000_0000; + let high = high.try_into().expect('u32s_to_u2562:overflow-high'); + u256 { high, low } +} + fn u64_array_slice(src: @Array, mut begin: usize, len: usize) -> Array { let mut slice = array![]; let end = begin + len; @@ -179,9 +180,7 @@ pub fn u128_array_slice(src: @Array, mut begin: usize, len: usize) -> Arra slice } -fn array_slice, impl TCopy: Copy>( - src: @Array, mut begin: usize, len: usize -) -> Array { +fn array_slice, +Copy>(src: @Array, mut begin: usize, len: usize) -> Array { let mut slice = array![]; let end = begin + len; while begin < end && begin < src.len() { diff --git a/packages/data_structures/Scarb.toml b/packages/data_structures/Scarb.toml index e439f270..b484f623 100644 --- a/packages/data_structures/Scarb.toml +++ b/packages/data_structures/Scarb.toml @@ -10,3 +10,6 @@ fmt.workspace = true [dependencies] alexandria_encoding = { path = "../encoding" } + +[dev-dependencies] +cairo_test.workspace = true diff --git a/packages/data_structures/src/array_ext.cairo b/packages/data_structures/src/array_ext.cairo index d21444a4..b8886add 100644 --- a/packages/data_structures/src/array_ext.cairo +++ b/packages/data_structures/src/array_ext.cairo @@ -9,7 +9,7 @@ pub trait ArrayTraitExt { fn pop_front_n(ref self: Array, n: usize) -> Array; /// Removes up to `n` elements from the front of `self`. fn remove_front_n(ref self: Array, n: usize); - /// Clones and appends all the elements of `self` and then `other` in a single new array. + /// Clones and appends all the elements of `self` and then `other` in a single new array. fn concat(self: @Array, other: @Array) -> Array; /// Return a new array containing the elements of `self` in a reversed order. fn reversed(self: @Array) -> Array; @@ -17,7 +17,7 @@ pub trait ArrayTraitExt { fn contains<+PartialEq>(self: @Array, item: @T) -> bool; /// Searches for an element in the array, returning its index. fn position<+PartialEq>(self: @Array, item: @T) -> Option; - /// Returns the number of elements in the array with the given value. + /// Returns the number of elements in the array with the given value. fn occurrences<+PartialEq>(self: @Array, item: @T) -> usize; /// Returns the minimum element of an array. fn min<+PartialOrd>(self: @Array) -> Option; @@ -27,7 +27,7 @@ pub trait ArrayTraitExt { fn max<+PartialOrd>(self: @Array) -> Option; /// Returns the position of the maximum element of an array. fn max_position<+PartialOrd>(self: @Array) -> Option; - /// Returns a new array, cloned from `self` but removes consecutive repeated elements. + /// Returns a new array, cloned from `self` but removes consecutive repeated elements. /// If the array is sorted, this removes all duplicates. fn dedup<+PartialEq>(self: @Array) -> Array; /// Returns a new array, cloned from `self` but without any duplicate. diff --git a/packages/data_structures/src/bit_array.cairo b/packages/data_structures/src/bit_array.cairo index 456d72a7..6e5e0fdd 100644 --- a/packages/data_structures/src/bit_array.cairo +++ b/packages/data_structures/src/bit_array.cairo @@ -1,5 +1,6 @@ use core::bytes_31::bytes31; use core::integer::u512; +use core::ops::index::IndexView; use core::serde::Serde; use core::serde::into_felt252_based::SerdeImpl; @@ -83,8 +84,8 @@ pub trait BitArrayTrait { /// `word` - The value to store onto the bit array of type `u512` /// `length` - The length of the word in bits, maximum 512 fn write_word_be_u512(ref self: BitArray, word: u512, length: usize); - /// Reads a single word of the specified length up to 248 bits in little endian bit representation - /// # Arguments + /// Reads a single word of the specified length up to 248 bits in little endian bit + /// representation # Arguments /// `length` - The bit length of the word to read, max 248 /// # Returns /// `Option` - If there are `length` bits remaining, the word is returned as felt252 @@ -96,7 +97,7 @@ pub trait BitArrayTrait { /// # Returns /// `Option` - If there are `length` bits remaining, the word is returned as u256 fn read_word_le_u256(ref self: BitArray, length: usize) -> Option; - /// Reads a single word of the specified length upto 512 bits in little endian representation. + /// Reads a single word of the specified length up to 512 bits in little endian representation. /// For words shorter than (or equal to) 256 bits consider the other read calls instead. /// # Arguments /// `length` - The bit length of the word to read, max 512 @@ -115,7 +116,7 @@ pub trait BitArrayTrait { /// `word` - The value to store onto the bit array of type `u256` /// `length` - The length of the word in bits, maximum 256 fn write_word_le_u256(ref self: BitArray, word: u256, length: usize); - /// Writes the bits of the specified length from `word` onto the BitArray + /// Writes the bits of the specified length from `word` onto the BitArray /// in little endian representation /// # Arguments /// `word` - The value to store onto the bit array of type `u512` @@ -458,7 +459,8 @@ impl BitArrayInternalImpl of BitArrayInternalTrait { } } -impl BitArrayIndexView of IndexView { +impl BitArrayIndexView of IndexView { + type Target = bool; fn index(self: @BitArray, index: usize) -> bool { self.at(index).expect('Index out of bounds') } diff --git a/packages/data_structures/src/byte_array_ext.cairo b/packages/data_structures/src/byte_array_ext.cairo index e48bfb44..bd93089a 100644 --- a/packages/data_structures/src/byte_array_ext.cairo +++ b/packages/data_structures/src/byte_array_ext.cairo @@ -25,11 +25,8 @@ pub impl ByteArrayIntoArrayU8 of Into> { fn into(self: ByteArray) -> Array { let mut reader = self.reader(); let mut result = array![]; - loop { - match reader.read_u8() { - Option::Some(byte) => result.append(byte), - Option::None => { break; }, - } + while let Option::Some(byte) = reader.read_u8() { + result.append(byte); }; result } diff --git a/packages/data_structures/src/byte_reader.cairo b/packages/data_structures/src/byte_reader.cairo index c84a5af1..51a79702 100644 --- a/packages/data_structures/src/byte_reader.cairo +++ b/packages/data_structures/src/byte_reader.cairo @@ -1,4 +1,5 @@ use core::integer::u512; +use core::ops::index::IndexView; use super::bit_array::{one_shift_left_bytes_felt252, one_shift_left_bytes_u128}; #[derive(Copy, Clone, Drop)] @@ -7,6 +8,7 @@ pub struct ByteReaderState { index: usize, } + pub trait ByteReader { /// Wraps the array of bytes in a ByteReader for sequential consumption of integers and/or bytes /// # Returns @@ -23,49 +25,57 @@ pub trait ByteReader { /// # Arguments /// * `offset` - the start location of the consecutive bytes to read /// # Returns - /// * `Option` - Returns an integer if there are enough consecutive bytes available in the ByteArray + /// * `Option` - Returns an integer if there are enough consecutive bytes available in the + /// ByteArray fn word_u16(self: @T, offset: usize) -> Option; /// Reads consecutive bytes from a specified offset as an unsigned integer in little endian /// # Arguments /// * `offset` - the start location of the consecutive bytes to read /// # Returns - /// * `Option` - Returns an integer if there are enough consecutive bytes available in the ByteArray + /// * `Option` - Returns an integer if there are enough consecutive bytes available in the + /// ByteArray fn word_u16_le(self: @T, offset: usize) -> Option; /// Reads consecutive bytes from a specified offset as an unsigned integer in big endian /// # Arguments /// * `offset` - the start location of the consecutive bytes to read /// # Returns - /// * `Option` - Returns an integer if there are enough consecutive bytes available in the ByteArray + /// * `Option` - Returns an integer if there are enough consecutive bytes available in the + /// ByteArray fn word_u32(self: @T, offset: usize) -> Option; /// Reads consecutive bytes from a specified offset as an unsigned integer in little endian /// # Arguments /// * `offset` - the start location of the consecutive bytes to read /// # Returns - /// * `Option` - Returns an integer if there are enough consecutive bytes available in the ByteArray + /// * `Option` - Returns an integer if there are enough consecutive bytes available in the + /// ByteArray fn word_u32_le(self: @T, offset: usize) -> Option; /// Reads consecutive bytes from a specified offset as an unsigned integer in big endian /// # Arguments /// * `offset` - the start location of the consecutive bytes to read /// # Returns - /// * `Option` - Returns an integer if there are enough consecutive bytes available in the ByteArray + /// * `Option` - Returns an integer if there are enough consecutive bytes available in the + /// ByteArray fn word_u64(self: @T, offset: usize) -> Option; /// Reads consecutive bytes from a specified offset as an unsigned integer in little endian /// # Arguments /// * `offset` - the start location of the consecutive bytes to read /// # Returns - /// * `Option` - Returns an integer if there are enough consecutive bytes available in the ByteArray + /// * `Option` - Returns an integer if there are enough consecutive bytes available in the + /// ByteArray fn word_u64_le(self: @T, offset: usize) -> Option; /// Reads consecutive bytes from a specified offset as an unsigned integer in big endian /// # Arguments /// * `offset` - the start location of the consecutive bytes to read /// # Returns - /// * `Option` - Returns an integer if there are enough consecutive bytes available in the ByteArray + /// * `Option` - Returns an integer if there are enough consecutive bytes available in the + /// ByteArray fn word_u128(self: @T, offset: usize) -> Option; /// Reads consecutive bytes from a specified offset as an unsigned integer in little endian /// # Arguments /// * `offset` - the start location of the consecutive bytes to read /// # Returns - /// * `Option` - Returns an integer if there are enough consecutive bytes available in the ByteArray + /// * `Option` - Returns an integer if there are enough consecutive bytes available in the + /// ByteArray fn word_u128_le(self: @T, offset: usize) -> Option; /// Reads a u8 unsigned integer /// # Returns @@ -123,36 +133,36 @@ pub trait ByteReader { /// # Returns /// `Option` - If there are enough bytes remaining an optional integer is returned fn read_i8(ref self: ByteReaderState) -> Option; - /// Reads an i16 signed integer in two's complement encoding from the ByteArray in big endian byte order - /// # Returns + /// Reads an i16 signed integer in two's complement encoding from the ByteArray in big endian + /// byte order # Returns /// `Option` - If there are enough bytes remaining an optional integer is returned fn read_i16(ref self: ByteReaderState) -> Option; - /// Reads an i16 signed integer in two's complement encoding from the ByteArray in little endian byte order - /// # Returns + /// Reads an i16 signed integer in two's complement encoding from the ByteArray in little endian + /// byte order # Returns /// `Option` - If there are enough bytes remaining an optional integer is returned fn read_i16_le(ref self: ByteReaderState) -> Option; - /// Reads an i32 signed integer in two's complement encoding from the ByteArray in big endian byte order - /// # Returns + /// Reads an i32 signed integer in two's complement encoding from the ByteArray in big endian + /// byte order # Returns /// `Option` - If there are enough bytes remaining an optional integer is returned fn read_i32(ref self: ByteReaderState) -> Option; - /// Reads an i32 signed integer in two's complement encoding from the ByteArray in little endian byte order - /// # Returns + /// Reads an i32 signed integer in two's complement encoding from the ByteArray in little endian + /// byte order # Returns /// `Option` - If there are enough bytes remaining an optional integer is returned fn read_i32_le(ref self: ByteReaderState) -> Option; - /// Reads an i64 signed integer in two's complement encoding from the ByteArray in big endian byte order - /// # Returns + /// Reads an i64 signed integer in two's complement encoding from the ByteArray in big endian + /// byte order # Returns /// `Option` - If there are enough bytes remaining an optional integer is returned fn read_i64(ref self: ByteReaderState) -> Option; - /// Reads an i64 signed integer in two's complement encoding from the ByteArray in little endian byte order - /// # Returns + /// Reads an i64 signed integer in two's complement encoding from the ByteArray in little endian + /// byte order # Returns /// `Option` - If there are enough bytes remaining an optional integer is returned fn read_i64_le(ref self: ByteReaderState) -> Option; - /// Reads an i128 signed integer in two's complement encoding from the ByteArray in big endian byte order - /// # Returns + /// Reads an i128 signed integer in two's complement encoding from the ByteArray in big endian + /// byte order # Returns /// `Option` - If there are enough bytes remaining an optional integer is returned fn read_i128(ref self: ByteReaderState) -> Option; - /// Reads an i128 signed integer in two's complement encoding from the ByteArray in little endian byte order - /// # Returns + /// Reads an i128 signed integer in two's complement encoding from the ByteArray in little + /// endian byte order # Returns /// `Option` - If there are enough bytes remaining an optional integer is returned fn read_i128_le(ref self: ByteReaderState) -> Option; /// Remaining length count relative to what has already been consume/read @@ -161,7 +171,9 @@ pub trait ByteReader { fn len(self: @ByteReaderState) -> usize; } -impl ByteReaderImpl, +Len, +IndexView> of ByteReader { +impl ByteReaderImpl< + T, +Drop, +Len, +IndexView, +Into::Target, @u8> +> of ByteReader { #[inline] fn reader(self: @T) -> ByteReaderState { ByteReaderState { data: self, index: 0 } @@ -175,8 +187,8 @@ impl ByteReaderImpl, +Len, +IndexView> of ByteRead #[inline] fn word_u16(self: @T, offset: usize) -> Option { if self.remaining(offset, 2) { - let b1 = *self[offset]; - let b2 = *self[offset + 1]; + let b1 = *self[offset].into(); + let b2 = *self[offset + 1].into(); Option::Some(b1.into() * one_shift_left_bytes_u128(1).try_into().unwrap() + b2.into()) } else { Option::None @@ -186,8 +198,8 @@ impl ByteReaderImpl, +Len, +IndexView> of ByteRead #[inline] fn word_u16_le(self: @T, offset: usize) -> Option { if self.remaining(offset, 2) { - let b1 = *self[offset]; - let b2 = *self[offset + 1]; + let b1 = *self[offset].into(); + let b2 = *self[offset + 1].into(); Option::Some(b1.into() + b2.into() * one_shift_left_bytes_u128(1).try_into().unwrap()) } else { Option::None @@ -197,10 +209,10 @@ impl ByteReaderImpl, +Len, +IndexView> of ByteRead #[inline] fn word_u32(self: @T, offset: usize) -> Option { if self.remaining(offset, 4) { - let b1 = *self[offset]; - let b2 = *self[offset + 1]; - let b3 = *self[offset + 2]; - let b4 = *self[offset + 3]; + let b1 = *self[offset].into(); + let b2 = *self[offset + 1].into(); + let b3 = *self[offset + 2].into(); + let b4 = *self[offset + 3].into(); Option::Some( b1.into() * one_shift_left_bytes_u128(3).try_into().unwrap() + b2.into() * one_shift_left_bytes_u128(2).try_into().unwrap() @@ -215,10 +227,10 @@ impl ByteReaderImpl, +Len, +IndexView> of ByteRead #[inline] fn word_u32_le(self: @T, offset: usize) -> Option { if self.remaining(offset, 4) { - let b1 = *self[offset]; - let b2 = *self[offset + 1]; - let b3 = *self[offset + 2]; - let b4 = *self[offset + 3]; + let b1 = *self[offset].into(); + let b2 = *self[offset + 1].into(); + let b3 = *self[offset + 2].into(); + let b4 = *self[offset + 3].into(); Option::Some( b1.into() + b2.into() * one_shift_left_bytes_u128(1).try_into().unwrap() @@ -233,14 +245,14 @@ impl ByteReaderImpl, +Len, +IndexView> of ByteRead #[inline] fn word_u64(self: @T, offset: usize) -> Option { if self.remaining(offset, 8) { - let b1 = *self[offset]; - let b2 = *self[offset + 1]; - let b3 = *self[offset + 2]; - let b4 = *self[offset + 3]; - let b5 = *self[offset + 4]; - let b6 = *self[offset + 5]; - let b7 = *self[offset + 6]; - let b8 = *self[offset + 7]; + let b1 = *self[offset].into(); + let b2 = *self[offset + 1].into(); + let b3 = *self[offset + 2].into(); + let b4 = *self[offset + 3].into(); + let b5 = *self[offset + 4].into(); + let b6 = *self[offset + 5].into(); + let b7 = *self[offset + 6].into(); + let b8 = *self[offset + 7].into(); Option::Some( b1.into() * one_shift_left_bytes_u128(7).try_into().unwrap() + b2.into() * one_shift_left_bytes_u128(6).try_into().unwrap() @@ -259,14 +271,14 @@ impl ByteReaderImpl, +Len, +IndexView> of ByteRead #[inline] fn word_u64_le(self: @T, offset: usize) -> Option { if self.remaining(offset, 8) { - let b1 = *self[offset]; - let b2 = *self[offset + 1]; - let b3 = *self[offset + 2]; - let b4 = *self[offset + 3]; - let b5 = *self[offset + 4]; - let b6 = *self[offset + 5]; - let b7 = *self[offset + 6]; - let b8 = *self[offset + 7]; + let b1 = *self[offset].into(); + let b2 = *self[offset + 1].into(); + let b3 = *self[offset + 2].into(); + let b4 = *self[offset + 3].into(); + let b5 = *self[offset + 4].into(); + let b6 = *self[offset + 5].into(); + let b7 = *self[offset + 6].into(); + let b8 = *self[offset + 7].into(); Option::Some( b1.into() + b2.into() * one_shift_left_bytes_u128(1).try_into().unwrap() @@ -285,22 +297,22 @@ impl ByteReaderImpl, +Len, +IndexView> of ByteRead #[inline] fn word_u128(self: @T, offset: usize) -> Option { if self.remaining(offset, 16) { - let b01 = *self[offset]; - let b02 = *self[offset + 1]; - let b03 = *self[offset + 2]; - let b04 = *self[offset + 3]; - let b05 = *self[offset + 4]; - let b06 = *self[offset + 5]; - let b07 = *self[offset + 6]; - let b08 = *self[offset + 7]; - let b09 = *self[offset + 8]; - let b10 = *self[offset + 9]; - let b11 = *self[offset + 10]; - let b12 = *self[offset + 11]; - let b13 = *self[offset + 12]; - let b14 = *self[offset + 13]; - let b15 = *self[offset + 14]; - let b16 = *self[offset + 15]; + let b01 = *self[offset].into(); + let b02 = *self[offset + 1].into(); + let b03 = *self[offset + 2].into(); + let b04 = *self[offset + 3].into(); + let b05 = *self[offset + 4].into(); + let b06 = *self[offset + 5].into(); + let b07 = *self[offset + 6].into(); + let b08 = *self[offset + 7].into(); + let b09 = *self[offset + 8].into(); + let b10 = *self[offset + 9].into(); + let b11 = *self[offset + 10].into(); + let b12 = *self[offset + 11].into(); + let b13 = *self[offset + 12].into(); + let b14 = *self[offset + 13].into(); + let b15 = *self[offset + 14].into(); + let b16 = *self[offset + 15].into(); Option::Some( b01.into() * one_shift_left_bytes_u128(15).try_into().unwrap() + b02.into() * one_shift_left_bytes_u128(14).try_into().unwrap() @@ -327,22 +339,22 @@ impl ByteReaderImpl, +Len, +IndexView> of ByteRead #[inline] fn word_u128_le(self: @T, offset: usize) -> Option { if self.remaining(offset, 16) { - let b01 = *self[offset]; - let b02 = *self[offset + 1]; - let b03 = *self[offset + 2]; - let b04 = *self[offset + 3]; - let b05 = *self[offset + 4]; - let b06 = *self[offset + 5]; - let b07 = *self[offset + 6]; - let b08 = *self[offset + 7]; - let b09 = *self[offset + 8]; - let b10 = *self[offset + 9]; - let b11 = *self[offset + 10]; - let b12 = *self[offset + 11]; - let b13 = *self[offset + 12]; - let b14 = *self[offset + 13]; - let b15 = *self[offset + 14]; - let b16 = *self[offset + 15]; + let b01 = *self[offset].into(); + let b02 = *self[offset + 1].into(); + let b03 = *self[offset + 2].into(); + let b04 = *self[offset + 3].into(); + let b05 = *self[offset + 4].into(); + let b06 = *self[offset + 5].into(); + let b07 = *self[offset + 6].into(); + let b08 = *self[offset + 7].into(); + let b09 = *self[offset + 8].into(); + let b10 = *self[offset + 9].into(); + let b11 = *self[offset + 10].into(); + let b12 = *self[offset + 11].into(); + let b13 = *self[offset + 12].into(); + let b14 = *self[offset + 13].into(); + let b15 = *self[offset + 14].into(); + let b16 = *self[offset + 15].into(); Option::Some( b01.into() + b02.into() * one_shift_left_bytes_u128(01).try_into().unwrap() @@ -368,7 +380,7 @@ impl ByteReaderImpl, +Len, +IndexView> of ByteRead fn read_u8(ref self: ByteReaderState) -> Option { if self.data.remaining(self.index, 1) { - let result = *self.data[self.index]; + let result = *self.data[self.index].into(); self.index += 1; Option::Some(result) } else { @@ -553,7 +565,8 @@ impl ByteArrayLenImpl of Len { impl ByteReaderLenImpl> of Len> { /// Returns the remaining length of the ByteReader /// # Returns - /// `usize` - The number of bytes remaining, considering the number of bytes that have already been consumed + /// `usize` - The number of bytes remaining, considering the number of bytes that have already + /// been consumed #[inline] fn len(self: @ByteReaderState) -> usize { let byte_array = *self.data; @@ -562,19 +575,10 @@ impl ByteReaderLenImpl> of Len> { } } -impl ByteArrayIndexViewAsSnapshotImpl of IndexView { - #[inline(always)] - fn index(self: @ByteArray, index: usize) -> @u8 { - @self.at(index).expect('Index out of bounds') - } -} - -impl ByteReaderIndexViewImpl< - T, impl TIndexView: IndexView -> of IndexView, usize, @u8> { +impl IntoU8Impl of Into { #[inline(always)] - fn index(self: @ByteReaderState, index: usize) -> @u8 { - TIndexView::index(*self.data, index) + fn into(self: u8) -> @u8 { + @self } } diff --git a/packages/data_structures/src/span_ext.cairo b/packages/data_structures/src/span_ext.cairo index 4bf57994..211b1ec5 100644 --- a/packages/data_structures/src/span_ext.cairo +++ b/packages/data_structures/src/span_ext.cairo @@ -1,7 +1,6 @@ use core::clone::Clone; use core::cmp::min; -use core::num::traits::OverflowingSub; -use core::option::OptionTrait; +use core::num::traits::CheckedSub; use super::array_ext::ArrayTraitExt; pub trait SpanTraitExt { @@ -13,7 +12,7 @@ pub trait SpanTraitExt { fn remove_front_n(ref self: Span, n: usize); /// Removes up to `n` elements from the back of `self`. fn remove_back_n(ref self: Span, n: usize); - /// Clones and appends all the elements of `self` and then `other` in a single new array. + /// Clones and appends all the elements of `self` and then `other` in a single new array. fn concat(self: Span, other: Span) -> Array; /// Return a new array containing the elements of `self` in a reversed order. fn reversed(self: Span) -> Array; @@ -21,7 +20,7 @@ pub trait SpanTraitExt { fn contains<+PartialEq>(self: Span, item: @T) -> bool; /// Searches for an element the span, returning its index. fn position<+PartialEq>(self: Span, item: @T) -> Option; - /// Returns the number of elements in the span with the given value. + /// Returns the number of elements in the span with the given value. fn occurrences<+PartialEq>(self: Span, item: @T) -> usize; /// Returns the minimum element of a span. fn min<+PartialOrd<@T>>(self: Span) -> Option; @@ -31,7 +30,7 @@ pub trait SpanTraitExt { fn max<+PartialOrd<@T>>(self: Span) -> Option; /// Returns the position of the maximum element of a span. fn max_position<+PartialOrd<@T>>(self: Span) -> Option; - /// Returns a new array, cloned from `self` but removes consecutive repeated elements. + /// Returns a new array, cloned from `self` but removes consecutive repeated elements. /// If the span is sorted, this removes all duplicates. fn dedup<+PartialEq>(self: Span) -> Array; /// Returns a new array, cloned from `self` but without any duplicate. @@ -52,14 +51,7 @@ impl SpanImpl, +Drop> of SpanTraitExt { fn pop_back_n(ref self: Span, n: usize) -> Span { let span_len = self.len(); // Saturating substraction - let separator = { - let (value, overflow) = span_len.overflowing_sub(n); - if overflow { - 0 - } else { - value - } - }; + let separator = span_len.checked_sub(n).unwrap_or(0); let res = self.slice(separator, span_len - separator); self = self.slice(0, separator); @@ -77,14 +69,7 @@ impl SpanImpl, +Drop> of SpanTraitExt { fn remove_back_n(ref self: Span, mut n: usize) { let span_len = self.len(); // Saturating substraction - let separator = { - let (value, overflow) = span_len.overflowing_sub(n); - if overflow { - 0 - } else { - value - } - }; + let separator = span_len.checked_sub(n).unwrap_or(0); self = self.slice(0, separator); } @@ -136,7 +121,7 @@ impl SpanImpl, +Drop> of SpanTraitExt { fn occurrences<+PartialEq>(mut self: Span, item: @T) -> usize { let mut count = 0_usize; - while let Option::Some(v) = self.pop_front() { + for v in self { if v == item { count += 1; } @@ -150,7 +135,7 @@ impl SpanImpl, +Drop> of SpanTraitExt { Option::None => { return Option::None; }, }; - while let Option::Some(item) = self.pop_front() { + for item in self { if item < min { min = item } @@ -166,14 +151,13 @@ impl SpanImpl, +Drop> of SpanTraitExt { Option::Some(item) => item, Option::None => { return Option::None; }, }; - while let Option::Some(item) = self - .pop_front() { - if item < min { - min_position = index + 1; - min = item; - } - index += 1; - }; + for item in self { + if item < min { + min_position = index + 1; + min = item; + } + index += 1; + }; Option::Some(min_position) } @@ -184,7 +168,7 @@ impl SpanImpl, +Drop> of SpanTraitExt { Option::None => { return Option::None; }, }; - while let Option::Some(item) = self.pop_front() { + for item in self { if item > max { max = item } @@ -201,14 +185,13 @@ impl SpanImpl, +Drop> of SpanTraitExt { Option::None => { return Option::None; }, }; - while let Option::Some(item) = self - .pop_front() { - if item > max { - max_position = index + 1; - max = item - } - index += 1; - }; + for item in self { + if item > max { + max_position = index + 1; + max = item + } + index += 1; + }; Option::Some(max_position) } @@ -222,13 +205,12 @@ impl SpanImpl, +Drop> of SpanTraitExt { let mut last_value = self.pop_front().unwrap(); let mut ret = array![last_value.clone()]; - while let Option::Some(v) = self - .pop_front() { - if (last_value != v) { - last_value = v; - ret.append(v.clone()); - } - }; + for v in self { + if (last_value != v) { + last_value = v; + ret.append(v.clone()); + } + }; ret } @@ -236,12 +218,11 @@ impl SpanImpl, +Drop> of SpanTraitExt { fn unique<+PartialEq>(mut self: Span) -> Array { let mut ret = array![]; - while let Option::Some(v) = self - .pop_front() { - if !ret.span().contains(v) { - ret.append(v.clone()); - } - }; + for v in self { + if !ret.span().contains(v) { + ret.append(v.clone()); + } + }; ret } diff --git a/packages/data_structures/src/tests.cairo b/packages/data_structures/src/tests.cairo index f902cc32..51f29f41 100644 --- a/packages/data_structures/src/tests.cairo +++ b/packages/data_structures/src/tests.cairo @@ -10,7 +10,7 @@ mod span_ext; mod stack; mod vec; -// Utilities +// Utilities #[inline(always)] fn get_felt252_array() -> Array { diff --git a/packages/data_structures/src/tests/bit_array.cairo b/packages/data_structures/src/tests/bit_array.cairo index df0bc09d..c2feb95c 100644 --- a/packages/data_structures/src/tests/bit_array.cairo +++ b/packages/data_structures/src/tests/bit_array.cairo @@ -1,8 +1,8 @@ use alexandria_data_structures::bit_array::{ BitArray, BitArrayTrait, one_shift_left_bytes_felt252, shift_bit }; -use core::integer::BoundedInt; use core::integer::u512; +use core::num::traits::Bounded; #[test] #[available_gas(30000000)] @@ -18,10 +18,7 @@ fn test_append_bit() { .try_into() .unwrap(); let expected: Array = array![val, val,]; - assert( - ba.current() == 0xa * one_shift_left_bytes_felt252(30) * shift_bit(4).into(), - 'expected current 0xa' - ); + assert_eq!(ba.current(), 0xa * one_shift_left_bytes_felt252(30) * shift_bit(4).into()); assert!(ba.data() == expected, "illegal array"); } @@ -32,7 +29,7 @@ fn test_at() { let mut index: usize = 0; loop { if index == 8 * 16 - 1 { - // last value + // last value assert!(ba[index] == false, "expected false"); break; } @@ -94,20 +91,14 @@ fn test_pop_front_empty() { #[available_gas(20000000)] fn test_read_word_be() { let mut ba = sample_bit_array(); - assert( - ba.read_word_be(length: 128).unwrap() == BoundedInt::::max().into() - 1, - 'expected max - 1' - ); + assert_eq!(ba.read_word_be(length: 128).unwrap(), Bounded::::MAX.into() - 1); } #[test] #[available_gas(20000000)] fn test_read_word_le() { let mut ba = sample_bit_array(); - assert( - ba.read_word_le(length: 128).unwrap() == 0x7fffffffffffffffffffffffffffffff, - 'unexpected value' - ); + assert_eq!(ba.read_word_le(length: 128).unwrap(), 0x7fffffffffffffffffffffffffffffff); } #[test] @@ -117,7 +108,7 @@ fn test_read_word_be_u256() { let low = 0x101112131415161718191a1b1c1d1e1f_u128; ba.write_word_be(low.into(), 128); let high = 0xfffffffffffffffffffffffffffffffe_u128; - assert!(ba.read_word_be_u256(length: 256).unwrap() == u256 { low, high }, "unexpected value"); + assert!(ba.read_word_be_u256(length: 256).unwrap() == u256 { low, high }); } #[test] @@ -127,7 +118,7 @@ fn test_read_word_le_u256() { let low = 0x7fffffffffffffffffffffffffffffff_u128; let high = 0x101112131415161718191a1b1c1d1e1f_u128; ba.write_word_le(high.into(), 128); - assert!(ba.read_word_le_u256(length: 256).unwrap() == u256 { low, high }, "unexpected value"); + assert!(ba.read_word_le_u256(length: 256).unwrap() == u256 { low, high }); } #[test] @@ -141,10 +132,7 @@ fn test_read_word_be_u512() { ba.write_word_be(limb1.into(), 128); ba.write_word_be(limb0.into(), 128); let limb3 = 0xfffffffffffffffffffffffffffffffe_u128; - assert( - ba.read_word_be_u512(length: 512).unwrap() == u512 { limb0, limb1, limb2, limb3 }, - 'unexpected value' - ); + assert!(ba.read_word_be_u512(length: 512).unwrap() == u512 { limb0, limb1, limb2, limb3 }); } #[test] @@ -158,10 +146,7 @@ fn test_read_word_le_u512() { ba.write_word_le(limb2.into(), 128); ba.write_word_le(limb3.into(), 128); let limb0 = 0x7fffffffffffffffffffffffffffffff_u128; - assert( - ba.read_word_le_u512(length: 512).unwrap() == u512 { limb0, limb1, limb2, limb3 }, - 'unexpected value' - ); + assert!(ba.read_word_le_u512(length: 512).unwrap() == u512 { limb0, limb1, limb2, limb3 }); } #[test] @@ -184,47 +169,39 @@ fn test_read_word_le_half() { #[available_gas(20000000)] fn test_write_word_be() { let mut ba: BitArray = Default::default(); - ba.write_word_be(BoundedInt::::max().into() - 2, 128); - assert( - ba.read_word_be(128).unwrap() == BoundedInt::::max().into() - 2, 'unexpected value' - ); + ba.write_word_be(Bounded::::MAX.into() - 2, 128); + assert_eq!(ba.read_word_be(128).unwrap(), Bounded::::MAX.into() - 2); } #[test] #[available_gas(20000000)] fn test_write_word_be_half() { let mut ba: BitArray = Default::default(); - ba.write_word_be(BoundedInt::::max().into() - 3, 64); - assert!( - ba.read_word_be(64).unwrap() == BoundedInt::::max().into() - 3, "unexpected value" - ); + ba.write_word_be(Bounded::::MAX.into() - 3, 64); + assert!(ba.read_word_be(64).unwrap() == Bounded::::MAX.into() - 3, "unexpected value"); } #[test] #[available_gas(20000000)] fn test_write_word_le() { let mut ba: BitArray = Default::default(); - ba.write_word_le(BoundedInt::::max().into() - 4, 128); - assert( - ba.read_word_le(128).unwrap() == BoundedInt::::max().into() - 4, 'unexpected value' - ); + ba.write_word_le(Bounded::::MAX.into() - 4, 128); + assert_eq!(ba.read_word_le(128).unwrap(), Bounded::::MAX.into() - 4); } #[test] #[available_gas(20000000)] fn test_write_word_le_half() { let mut ba: BitArray = Default::default(); - ba.write_word_le(BoundedInt::::max().into() - 5, 64); - assert!( - ba.read_word_le(64).unwrap() == BoundedInt::::max().into() - 5, "unexpected value" - ); + ba.write_word_le(Bounded::::MAX.into() - 5, 64); + assert!(ba.read_word_le(64).unwrap() == Bounded::::MAX.into() - 5, "unexpected value"); } #[test] #[available_gas(40000000)] fn test_write_word_be_u256() { let mut ba: BitArray = Default::default(); - let expected = u256 { low: BoundedInt::max() - 1, high: BoundedInt::max() - 2 }; + let expected = u256 { low: Bounded::MAX - 1, high: Bounded::MAX - 2 }; ba.write_word_be_u256(expected, 256); assert!(ba.read_word_be_u256(256).unwrap() == expected, "unexpected value"); } @@ -233,7 +210,7 @@ fn test_write_word_be_u256() { #[available_gas(40000000)] fn test_write_word_le_u256() { let mut ba: BitArray = Default::default(); - let expected = u256 { low: BoundedInt::max() - 1, high: BoundedInt::max() - 2 }; + let expected = u256 { low: Bounded::MAX - 1, high: Bounded::MAX - 2 }; ba.write_word_le_u256(expected, 256); assert!(ba.read_word_le_u256(256).unwrap() == expected, "unexpected value"); } @@ -242,10 +219,10 @@ fn test_write_word_le_u256() { #[available_gas(80000000)] fn test_write_word_be_u512() { let mut ba: BitArray = Default::default(); - let limb0 = BoundedInt::::max(); - let limb1 = BoundedInt::::max() - 1; - let limb2 = BoundedInt::::max() - 2; - let limb3 = BoundedInt::::max() - 3; + let limb0 = Bounded::::MAX; + let limb1 = Bounded::::MAX - 1; + let limb2 = Bounded::::MAX - 2; + let limb3 = Bounded::::MAX - 3; let expected = u512 { limb0, limb1, limb2, limb3 }; ba.write_word_be_u512(expected, 512); assert!(ba.read_word_be_u512(512).unwrap() == expected, "unexpected value"); @@ -255,10 +232,10 @@ fn test_write_word_be_u512() { #[available_gas(80000000)] fn test_write_word_le_u512() { let mut ba: BitArray = Default::default(); - let limb0 = BoundedInt::::max(); - let limb1 = BoundedInt::::max() - 1; - let limb2 = BoundedInt::::max() - 2; - let limb3 = BoundedInt::::max() - 3; + let limb0 = Bounded::::MAX; + let limb1 = Bounded::::MAX - 1; + let limb2 = Bounded::::MAX - 2; + let limb3 = Bounded::::MAX - 3; let expected = u512 { limb0, limb1, limb2, limb3 }; ba.write_word_le_u512(expected, 512); assert!(ba.read_word_le_u512(512).unwrap() == expected, "unexpected value"); @@ -298,7 +275,7 @@ fn test_serde_serialize() { // We gotta skip one now out.pop_front().unwrap(); let data: felt252 = out.pop_front().unwrap(); - let expected: felt252 = BoundedInt::::max().into() - 1; + let expected: felt252 = Bounded::::MAX.into() - 1; let expected = expected * one_shift_left_bytes_felt252(15); assert!(data == expected, "unexpected data"); } @@ -329,6 +306,6 @@ fn test_serde_ser_deser() { // helpers fn sample_bit_array() -> BitArray { - let sample: felt252 = BoundedInt::::max().into() - 1; + let sample: felt252 = Bounded::::MAX.into() - 1; BitArrayTrait::new(array![], sample * one_shift_left_bytes_felt252(15), 0, 8 * 16) } diff --git a/packages/data_structures/src/tests/byte_appender.cairo b/packages/data_structures/src/tests/byte_appender.cairo index 0ed859fd..fb70058b 100644 --- a/packages/data_structures/src/tests/byte_appender.cairo +++ b/packages/data_structures/src/tests/byte_appender.cairo @@ -13,7 +13,7 @@ fn test_append_u16() { ba.append_u16(0x0304_u16); ba.append_u16(0x0506_u16); ba.append_u16(0x0708_u16); - assert_eq!(ba, test_byte_array_8(), "u16 differs"); + assert_eq!(ba, test_byte_array_8()); } #[test] @@ -24,7 +24,7 @@ fn test_append_u16_arr() { ba.append_u16(0x0304_u16); ba.append_u16(0x0506_u16); ba.append_u16(0x0708_u16); - assert_eq!(ba, test_array_8(), "u16 differs"); + assert_eq!(ba, test_array_8()); } #[test] @@ -35,7 +35,7 @@ fn test_append_u16_le() { ba.append_u16_le(0x0403_u16); ba.append_u16_le(0x0605_u16); ba.append_u16_le(0x0807_u16); - assert_eq!(ba, test_byte_array_8(), "u16 differs"); + assert_eq!(ba, test_byte_array_8()); } #[test] @@ -46,7 +46,7 @@ fn test_append_u16_le_arr() { ba.append_u16_le(0x0403_u16); ba.append_u16_le(0x0605_u16); ba.append_u16_le(0x0807_u16); - assert_eq!(ba, test_array_8(), "u16 differs"); + assert_eq!(ba, test_array_8()); } #[test] @@ -55,7 +55,7 @@ fn test_append_u32() { let mut ba: ByteArray = Default::default(); ba.append_u32(0x01020304_u32); ba.append_u32(0x05060708_u32); - assert_eq!(ba, test_byte_array_8(), "u32 differs"); + assert_eq!(ba, test_byte_array_8()); } #[test] @@ -64,7 +64,7 @@ fn test_append_u32_arr() { let mut ba: Array = array![]; ba.append_u32(0x01020304_u32); ba.append_u32(0x05060708_u32); - assert_eq!(ba, test_array_8(), "u32 differs"); + assert_eq!(ba, test_array_8()); } #[test] @@ -73,7 +73,7 @@ fn test_append_u32_le() { let mut ba: ByteArray = Default::default(); ba.append_u32_le(0x04030201_u32); ba.append_u32_le(0x08070605_u32); - assert_eq!(ba, test_byte_array_8(), "u32 differs"); + assert_eq!(ba, test_byte_array_8()); } #[test] @@ -82,7 +82,7 @@ fn test_append_u32_le_arr() { let mut ba: Array = array![]; ba.append_u32_le(0x04030201_u32); ba.append_u32_le(0x08070605_u32); - assert_eq!(ba, test_array_8(), "u32 differs"); + assert_eq!(ba, test_array_8()); } #[test] @@ -91,7 +91,7 @@ fn test_append_u64() { let mut ba: ByteArray = Default::default(); ba.append_u64(0x0102030405060708_u64); ba.append_u64(0x090a0b0c0d0e0f10_u64); - assert_eq!(ba, test_byte_array_16(), "u64 differs"); + assert_eq!(ba, test_byte_array_16()); } #[test] @@ -100,7 +100,7 @@ fn test_append_u64_arr() { let mut ba: Array = array![]; ba.append_u64(0x0102030405060708_u64); ba.append_u64(0x090a0b0c0d0e0f10_u64); - assert_eq!(ba, test_array_16(), "u64 differs"); + assert_eq!(ba, test_array_16()); } #[test] @@ -109,7 +109,7 @@ fn test_append_u64_le() { let mut ba: ByteArray = Default::default(); ba.append_u64_le(0x0807060504030201_u64); ba.append_u64_le(0x100f0e0d0c0b0a09_u64); - assert_eq!(ba, test_byte_array_16(), "u64 differs"); + assert_eq!(ba, test_byte_array_16()); } #[test] @@ -118,7 +118,7 @@ fn test_append_u64_le_arr() { let mut ba: Array = array![]; ba.append_u64_le(0x0807060504030201_u64); ba.append_u64_le(0x100f0e0d0c0b0a09_u64); - assert_eq!(ba, test_array_16(), "u64 differs"); + assert_eq!(ba, test_array_16()); } #[test] @@ -127,7 +127,7 @@ fn test_append_u128() { let mut ba: ByteArray = Default::default(); ba.append_u128(0x0102030405060708090a0b0c0d0e0f10_u128); ba.append_u128(0x1112131415161718191a1b1c1d1e1f20_u128); - assert_eq!(ba, test_byte_array_32(), "u128 differs"); + assert_eq!(ba, test_byte_array_32()); } #[test] @@ -136,7 +136,7 @@ fn test_append_u128_arr() { let mut ba: Array = array![]; ba.append_u128(0x0102030405060708090a0b0c0d0e0f10_u128); ba.append_u128(0x1112131415161718191a1b1c1d1e1f20_u128); - assert_eq!(ba, test_array_32(), "u128 differs"); + assert_eq!(ba, test_array_32()); } #[test] @@ -145,7 +145,7 @@ fn test_append_u128_le() { let mut ba: ByteArray = Default::default(); ba.append_u128_le(0x100f0e0d0c0b0a090807060504030201_u128); ba.append_u128_le(0x201f1e1d1c1b1a191817161514131211_u128); - assert_eq!(ba, test_byte_array_32(), "u128 differs"); + assert_eq!(ba, test_byte_array_32()); } #[test] @@ -154,7 +154,7 @@ fn test_append_u128_le_arr() { let mut ba: Array = array![]; ba.append_u128_le(0x100f0e0d0c0b0a090807060504030201_u128); ba.append_u128_le(0x201f1e1d1c1b1a191817161514131211_u128); - assert_eq!(ba, test_array_32(), "u128 differs"); + assert_eq!(ba, test_array_32()); } #[test] @@ -165,7 +165,7 @@ fn test_append_u256() { high: 0x0102030405060708090a0b0c0d0e0f10_u128, low: 0x1112131415161718191a1b1c1d1e1f20_u128, }; ba.append_u256(word); - assert_eq!(ba, test_byte_array_32(), "u256 differs"); + assert_eq!(ba, test_byte_array_32()); } #[test] @@ -176,7 +176,7 @@ fn test_append_u256_arr() { high: 0x0102030405060708090a0b0c0d0e0f10_u128, low: 0x1112131415161718191a1b1c1d1e1f20_u128, }; ba.append_u256(word); - assert_eq!(ba, test_array_32(), "u256 differs"); + assert_eq!(ba, test_array_32()); } #[test] @@ -187,7 +187,7 @@ fn test_append_u256_le() { low: 0x100f0e0d0c0b0a090807060504030201_u128, high: 0x201f1e1d1c1b1a191817161514131211_u128, }; ba.append_u256_le(word); - assert_eq!(ba, test_byte_array_32(), "u256 differs"); + assert_eq!(ba, test_byte_array_32()); } #[test] @@ -198,7 +198,7 @@ fn test_append_u256_le_arr() { low: 0x100f0e0d0c0b0a090807060504030201_u128, high: 0x201f1e1d1c1b1a191817161514131211_u128, }; ba.append_u256_le(word); - assert_eq!(ba, test_array_32(), "u256 differs"); + assert_eq!(ba, test_array_32()); } #[test] @@ -213,7 +213,7 @@ fn test_append_u512() { let mut ba: ByteArray = Default::default(); ba.append_u512(test64); - assert_eq!(ba, test_byte_array_64(), "test64 differs"); + assert_eq!(ba, test_byte_array_64()); } #[test] @@ -228,7 +228,7 @@ fn test_append_u512_arr() { let mut ba: Array = array![]; ba.append_u512(test64); - assert_eq!(ba, test_array_64(), "test64 differs"); + assert_eq!(ba, test_array_64()); } #[test] @@ -243,7 +243,7 @@ fn test_append_u512_le() { let mut ba: ByteArray = Default::default(); ba.append_u512_le(test64); - assert_eq!(ba, test_byte_array_64(), "test64 differs"); + assert_eq!(ba, test_byte_array_64()); } #[test] @@ -258,7 +258,7 @@ fn test_append_u512_le_arr() { let mut ba: Array = array![]; ba.append_u512_le(test64); - assert_eq!(ba, test_array_64(), "test64 differs"); + assert_eq!(ba, test_array_64()); } #[test] @@ -268,7 +268,7 @@ fn test_append_i8() { ba1.append_i8(127_i8); let mut ba2: ByteArray = Default::default(); ba2.append_byte(0x7f_u8); - assert_eq!(ba1, ba2, "i8 differs"); + assert_eq!(ba1, ba2); } #[test] @@ -278,7 +278,7 @@ fn test_append_i8_arr() { ba1.append_i8(127_i8); let mut ba2: Array = array![]; ba2.append(0x7f_u8); - assert_eq!(ba1, ba2, "i8 differs"); + assert_eq!(ba1, ba2); } #[test] @@ -288,7 +288,7 @@ fn test_append_i8_neg() { ba1.append_i8(-128_i8); let mut ba2: ByteArray = Default::default(); ba2.append_byte(0x80_u8); - assert_eq!(ba1, ba2, "negative i8 differs"); + assert_eq!(ba1, ba2); } #[test] @@ -298,7 +298,7 @@ fn test_append_i8_neg_arr() { ba1.append_i8(-128_i8); let mut ba2: Array = array![]; ba2.append(0x80_u8); - assert_eq!(ba1, ba2, "negative i8 differs"); + assert_eq!(ba1, ba2); } #[test] @@ -309,7 +309,7 @@ fn test_append_i16() { ba1.append_i16(0x0304_i16); ba1.append_i16(0x0506_i16); ba1.append_i16(0x0708_i16); - assert_eq!(ba1, test_byte_array_8(), "i16 differs"); + assert_eq!(ba1, test_byte_array_8()); } #[test] @@ -320,7 +320,7 @@ fn test_append_i16_arr() { ba1.append_i16(0x0304_i16); ba1.append_i16(0x0506_i16); ba1.append_i16(0x0708_i16); - assert_eq!(ba1, test_array_8(), "i16 differs"); + assert_eq!(ba1, test_array_8()); } #[test] @@ -331,7 +331,7 @@ fn test_append_i16_le() { ba1.append_i16_le(0x0403_i16); ba1.append_i16_le(0x0605_i16); ba1.append_i16_le(0x0807_i16); - assert_eq!(ba1, test_byte_array_8(), "i16 differs"); + assert_eq!(ba1, test_byte_array_8()); } #[test] @@ -342,7 +342,7 @@ fn test_append_i16_le_arr() { ba1.append_i16_le(0x0403_i16); ba1.append_i16_le(0x0605_i16); ba1.append_i16_le(0x0807_i16); - assert_eq!(ba1, test_array_8(), "i16 differs"); + assert_eq!(ba1, test_array_8()); } #[test] @@ -357,7 +357,7 @@ fn test_append_i16_neg() { ba1.append_i16(-1_i16); ba1.append_i16(-1_i16); ba1.append_i16(-2_i16); - assert_eq!(ba1, test_byte_array_16_neg(), "negative i16 differs"); + assert_eq!(ba1, test_byte_array_16_neg()); } #[test] @@ -372,7 +372,7 @@ fn test_append_i16_neg_arr() { ba1.append_i16(-1_i16); ba1.append_i16(-1_i16); ba1.append_i16(-2_i16); - assert_eq!(ba1, test_array_16_neg(), "negative i16 differs"); + assert_eq!(ba1, test_array_16_neg()); } #[test] @@ -387,7 +387,7 @@ fn test_append_i16_le_neg() { ba1.append_i16_le(-1_i16); ba1.append_i16_le(-1_i16); ba1.append_i16_le(-257_i16); - assert_eq!(ba1, test_byte_array_16_neg(), "negative i16 differs"); + assert_eq!(ba1, test_byte_array_16_neg()); } #[test] @@ -402,7 +402,7 @@ fn test_append_i16_le_neg_arr() { ba1.append_i16_le(-1_i16); ba1.append_i16_le(-1_i16); ba1.append_i16_le(-257_i16); - assert_eq!(ba1, test_array_16_neg(), "negative i16 differs"); + assert_eq!(ba1, test_array_16_neg()); } #[test] @@ -411,7 +411,7 @@ fn test_append_i32() { let mut ba: ByteArray = Default::default(); ba.append_i32(0x01020304_i32); ba.append_i32(0x05060708_i32); - assert_eq!(ba, test_byte_array_8(), "i32 differs"); + assert_eq!(ba, test_byte_array_8()); } #[test] @@ -420,7 +420,7 @@ fn test_append_i32_arr() { let mut ba: Array = array![]; ba.append_i32(0x01020304_i32); ba.append_i32(0x05060708_i32); - assert_eq!(ba, test_array_8(), "i32 differs"); + assert_eq!(ba, test_array_8()); } #[test] @@ -429,7 +429,7 @@ fn test_append_i32_le() { let mut ba: ByteArray = Default::default(); ba.append_i32_le(0x04030201_i32); ba.append_i32_le(0x08070605_i32); - assert_eq!(ba, test_byte_array_8(), "i32 differs"); + assert_eq!(ba, test_byte_array_8()); } #[test] @@ -438,7 +438,7 @@ fn test_append_i32_le_arr() { let mut ba: Array = array![]; ba.append_i32_le(0x04030201_i32); ba.append_i32_le(0x08070605_i32); - assert_eq!(ba, test_array_8(), "i32 differs"); + assert_eq!(ba, test_array_8()); } #[test] @@ -449,7 +449,7 @@ fn test_append_i32_neg() { ba.append_i32(-1_i32); ba.append_i32(-1_i32); ba.append_i32(-2_i32); - assert_eq!(ba, test_byte_array_16_neg(), "negative i32 differs"); + assert_eq!(ba, test_byte_array_16_neg()); } #[test] #[available_gas(1000000)] @@ -459,7 +459,7 @@ fn test_append_i32_neg_arr() { ba.append_i32(-1_i32); ba.append_i32(-1_i32); ba.append_i32(-2_i32); - assert_eq!(ba, test_array_16_neg(), "negative i32 differs"); + assert_eq!(ba, test_array_16_neg()); } #[test] @@ -470,7 +470,7 @@ fn test_append_i32_le_neg() { ba.append_i32_le(-1_i32); ba.append_i32_le(-1_i32); ba.append_i32_le(-16777217_i32); - assert_eq!(ba, test_byte_array_16_neg(), "negative i32 differs"); + assert_eq!(ba, test_byte_array_16_neg()); } #[test] @@ -481,7 +481,7 @@ fn test_append_i32_le_neg_arr() { ba.append_i32_le(-1_i32); ba.append_i32_le(-1_i32); ba.append_i32_le(-16777217_i32); - assert_eq!(ba, test_array_16_neg(), "negative i32 differs"); + assert_eq!(ba, test_array_16_neg()); } #[test] @@ -490,7 +490,7 @@ fn test_append_i64() { let mut ba: ByteArray = Default::default(); ba.append_i64(0x0102030405060708_i64); ba.append_i64(0x090a0b0c0d0e0f10_i64); - assert_eq!(ba, test_byte_array_16(), "i64 differs"); + assert_eq!(ba, test_byte_array_16()); } #[test] @@ -499,7 +499,7 @@ fn test_append_i64_arr() { let mut ba: Array = array![]; ba.append_i64(0x0102030405060708_i64); ba.append_i64(0x090a0b0c0d0e0f10_i64); - assert_eq!(ba, test_array_16(), "i64 differs"); + assert_eq!(ba, test_array_16()); } #[test] @@ -508,7 +508,7 @@ fn test_append_i64_le() { let mut ba: ByteArray = Default::default(); ba.append_i64_le(0x0807060504030201_i64); ba.append_i64_le(0x100f0e0d0c0b0a09_i64); - assert_eq!(ba, test_byte_array_16(), "i64 differs"); + assert_eq!(ba, test_byte_array_16()); } #[test] @@ -517,7 +517,7 @@ fn test_append_i64_le_arr() { let mut ba: Array = array![]; ba.append_i64_le(0x0807060504030201_i64); ba.append_i64_le(0x100f0e0d0c0b0a09_i64); - assert_eq!(ba, test_array_16(), "i64 differs"); + assert_eq!(ba, test_array_16()); } #[test] @@ -526,7 +526,7 @@ fn test_append_i64_neg() { let mut ba: ByteArray = Default::default(); ba.append_i64(-1_i64); ba.append_i64(-2_i64); - assert_eq!(ba, test_byte_array_16_neg(), "negative i64 differs"); + assert_eq!(ba, test_byte_array_16_neg()); } #[test] @@ -535,7 +535,7 @@ fn test_append_i64_neg_arr() { let mut ba: Array = array![]; ba.append_i64(-1_i64); ba.append_i64(-2_i64); - assert_eq!(ba, test_array_16_neg(), "negative i64 differs"); + assert_eq!(ba, test_array_16_neg()); } #[test] @@ -544,7 +544,7 @@ fn test_append_i64_le_neg() { let mut ba: ByteArray = Default::default(); ba.append_i64_le(-1_i64); ba.append_i64_le(-72057594037927937_i64); - assert_eq!(ba, test_byte_array_16_neg(), "negative i64 differs"); + assert_eq!(ba, test_byte_array_16_neg()); } #[test] @@ -553,7 +553,7 @@ fn test_append_i64_le_neg_arr() { let mut ba: Array = array![]; ba.append_i64_le(-1_i64); ba.append_i64_le(-72057594037927937_i64); - assert_eq!(ba, test_array_16_neg(), "negative i64 differs"); + assert_eq!(ba, test_array_16_neg()); } #[test] @@ -562,7 +562,7 @@ fn test_append_i128() { let mut ba: ByteArray = Default::default(); ba.append_i128(0x0102030405060708090a0b0c0d0e0f10_i128); ba.append_i128(0x1112131415161718191a1b1c1d1e1f20_i128); - assert_eq!(ba, test_byte_array_32(), "i128 differs"); + assert_eq!(ba, test_byte_array_32()); } #[test] @@ -571,7 +571,7 @@ fn test_append_i128_arr() { let mut ba: Array = array![]; ba.append_i128(0x0102030405060708090a0b0c0d0e0f10_i128); ba.append_i128(0x1112131415161718191a1b1c1d1e1f20_i128); - assert_eq!(ba, test_array_32(), "i128 differs"); + assert_eq!(ba, test_array_32()); } #[test] @@ -580,7 +580,7 @@ fn test_append_i128_le() { let mut ba: ByteArray = Default::default(); ba.append_i128_le(0x100f0e0d0c0b0a090807060504030201_i128); ba.append_i128_le(0x201f1e1d1c1b1a191817161514131211_i128); - assert_eq!(ba, test_byte_array_32(), "i128 differs"); + assert_eq!(ba, test_byte_array_32()); } #[test] @@ -589,7 +589,7 @@ fn test_append_i128_le_arr() { let mut ba: Array = array![]; ba.append_i128_le(0x100f0e0d0c0b0a090807060504030201_i128); ba.append_i128_le(0x201f1e1d1c1b1a191817161514131211_i128); - assert_eq!(ba, test_array_32(), "i128 differs"); + assert_eq!(ba, test_array_32()); } #[test] @@ -597,7 +597,7 @@ fn test_append_i128_le_arr() { fn test_append_i128_neg() { let mut ba: ByteArray = Default::default(); ba.append_i128(-2_i128); - assert_eq!(ba, test_byte_array_16_neg(), "negative i128 differs"); + assert_eq!(ba, test_byte_array_16_neg()); } #[test] @@ -605,7 +605,7 @@ fn test_append_i128_neg() { fn test_append_i128_neg_arr() { let mut ba: Array = array![]; ba.append_i128(-2_i128); - assert_eq!(ba, test_array_16_neg(), "negative i128 differs"); + assert_eq!(ba, test_array_16_neg()); } #[test] @@ -613,7 +613,7 @@ fn test_append_i128_neg_arr() { fn test_append_i128_le_neg() { let mut ba: ByteArray = Default::default(); ba.append_i128_le(-1329227995784915872903807060280344577_i128); - assert_eq!(ba, test_byte_array_16_neg(), "negative i128 differs"); + assert_eq!(ba, test_byte_array_16_neg()); } #[test] @@ -621,5 +621,5 @@ fn test_append_i128_le_neg() { fn test_append_i128_le_neg_arr() { let mut ba: Array = array![]; ba.append_i128_le(-1329227995784915872903807060280344577_i128); - assert_eq!(ba, test_array_16_neg(), "negative i128 differs"); + assert_eq!(ba, test_array_16_neg()); } diff --git a/packages/data_structures/src/tests/byte_array_ext.cairo b/packages/data_structures/src/tests/byte_array_ext.cairo index 678d81d3..ce74a13a 100644 --- a/packages/data_structures/src/tests/byte_array_ext.cairo +++ b/packages/data_structures/src/tests/byte_array_ext.cairo @@ -6,11 +6,8 @@ fn test_span_u8_into_byte_array() { let array: Array = array![1, 2, 3, 4, 5, 6, 7, 8,]; let ba: ByteArray = array.span().into(); let mut index = 0_usize; - loop { - match ba.at(index) { - Option::Some(byte) => assert(*(array[index]) == byte, 'should equal'), - Option::None => { break; } - }; + while let Option::Some(byte) = ba.at(index) { + assert!(*(array[index]) == byte); index += 1; }; } diff --git a/packages/data_structures/src/tests/byte_reader.cairo b/packages/data_structures/src/tests/byte_reader.cairo index a35305b3..965ad745 100644 --- a/packages/data_structures/src/tests/byte_reader.cairo +++ b/packages/data_structures/src/tests/byte_reader.cairo @@ -379,16 +379,10 @@ fn test_read_sequence() { let ba = test_byte_array_64(); let mut rd = ba.reader(); assert!(rd.read_i8() == Option::Some(1), "expected 1"); - assert( - rd.read_i128() == Option::Some(0x02030405060708090a0b0c0d0e0f1011), 'not 0x0203040506...' - ); - assert( - rd.read_u128() == Option::Some(0x12131415161718191a1b1c1d1e1f2021), 'not 0x1213141516...' - ); - assert!(rd.read_i64() == Option::Some(0x2223242526272829), "not 0x22232425..."); - assert( - rd.read_u128() == Option::Some(0x2a2b2c2d2e2f30313233343536373839), 'not 0x2a2b2c2d2e...' - ); + assert!(rd.read_i128() == Option::Some(0x02030405060708090a0b0c0d0e0f1011)); + assert!(rd.read_u128() == Option::Some(0x12131415161718191a1b1c1d1e1f2021)); + assert!(rd.read_i64() == Option::Some(0x2223242526272829)); + assert!(rd.read_u128() == Option::Some(0x2a2b2c2d2e2f30313233343536373839)); assert!(rd.read_u32() == Option::Some(0x3a3b3c3d), "not 0x3a3b3c3d"); assert!(rd.read_i16() == Option::Some(0x3e3f), "not 0x3e3f"); assert!(rd.read_u8() == Option::Some(0x40), "not 0x40"); @@ -401,16 +395,10 @@ fn test_read_sequence_arr() { let ba = test_array_64(); let mut rd = ba.reader(); assert!(rd.read_i8() == Option::Some(1), "expected 1"); - assert( - rd.read_i128() == Option::Some(0x02030405060708090a0b0c0d0e0f1011), 'not 0x0203040506...' - ); - assert( - rd.read_u128() == Option::Some(0x12131415161718191a1b1c1d1e1f2021), 'not 0x1213141516...' - ); + assert!(rd.read_i128() == Option::Some(0x02030405060708090a0b0c0d0e0f1011)); + assert!(rd.read_u128() == Option::Some(0x12131415161718191a1b1c1d1e1f2021)); assert!(rd.read_i64() == Option::Some(0x2223242526272829), "not 0x22232425..."); - assert( - rd.read_u128() == Option::Some(0x2a2b2c2d2e2f30313233343536373839), 'not 0x2a2b2c2d2e...' - ); + assert!(rd.read_u128() == Option::Some(0x2a2b2c2d2e2f30313233343536373839)); assert!(rd.read_u32() == Option::Some(0x3a3b3c3d), "not 0x3a3b3c3d"); assert!(rd.read_i16() == Option::Some(0x3e3f), "not 0x3e3f"); assert!(rd.read_u8() == Option::Some(0x40), "not 0x40"); @@ -423,16 +411,10 @@ fn test_read_sequence_le() { let ba = test_byte_array_64(); let mut rd = ba.reader(); assert!(rd.read_i8() == Option::Some(1), "expected 1"); - assert( - rd.read_i128_le() == Option::Some(0x11100f0e0d0c0b0a0908070605040302), 'not 0x11100f0e0...' - ); - assert( - rd.read_u128_le() == Option::Some(0x21201f1e1d1c1b1a1918171615141312), 'not 0x21201f1e1d...' - ); + assert!(rd.read_i128_le() == Option::Some(0x11100f0e0d0c0b0a0908070605040302)); + assert!(rd.read_u128_le() == Option::Some(0x21201f1e1d1c1b1a1918171615141312)); assert!(rd.read_i64_le() == Option::Some(0x2928272625242322), "not 0x29282726..."); - assert( - rd.read_u128_le() == Option::Some(0x393837363534333231302f2e2d2c2b2a), 'not 0x3938373635...' - ); + assert!(rd.read_u128_le() == Option::Some(0x393837363534333231302f2e2d2c2b2a)); assert!(rd.read_u32_le() == Option::Some(0x3d3c3b3a), "not 0x3d3c3b3a"); assert!(rd.read_i16_le() == Option::Some(0x3f3e), "not 0x3f3e"); assert!(rd.read_u8() == Option::Some(0x40), "not 0x40"); @@ -445,16 +427,10 @@ fn test_read_sequence_le_arr() { let ba = test_array_64(); let mut rd = ba.reader(); assert!(rd.read_i8() == Option::Some(1), "expected 1"); - assert( - rd.read_i128_le() == Option::Some(0x11100f0e0d0c0b0a0908070605040302), 'not 0x11100f0e0...' - ); - assert( - rd.read_u128_le() == Option::Some(0x21201f1e1d1c1b1a1918171615141312), 'not 0x21201f1e1d...' - ); + assert!(rd.read_i128_le() == Option::Some(0x11100f0e0d0c0b0a0908070605040302)); + assert!(rd.read_u128_le() == Option::Some(0x21201f1e1d1c1b1a1918171615141312)); assert!(rd.read_i64_le() == Option::Some(0x2928272625242322), "not 0x29282726..."); - assert( - rd.read_u128_le() == Option::Some(0x393837363534333231302f2e2d2c2b2a), 'not 0x3938373635...' - ); + assert!(rd.read_u128_le() == Option::Some(0x393837363534333231302f2e2d2c2b2a)); assert!(rd.read_u32_le() == Option::Some(0x3d3c3b3a), "not 0x3d3c3b3a"); assert!(rd.read_i16_le() == Option::Some(0x3f3e), "not 0x3f3e"); assert!(rd.read_u8() == Option::Some(0x40), "not 0x40"); diff --git a/packages/data_structures/src/tests/queue.cairo b/packages/data_structures/src/tests/queue.cairo index 90b73208..2387e7e5 100644 --- a/packages/data_structures/src/tests/queue.cairo +++ b/packages/data_structures/src/tests/queue.cairo @@ -6,7 +6,7 @@ fn queue_new_test() { let queue = QueueTrait::::new(); let result_len = queue.len(); - assert_eq!(result_len, 0, "wrong length"); + assert_eq!(result_len, 0); } #[test] @@ -26,7 +26,7 @@ fn queue_enqueue_test() { queue.enqueue(2); assert!(!queue.is_empty(), "must not be empty"); - assert_eq!(queue.len(), 2, "len should be 2"); + assert_eq!(queue.len(), 2); } #[test] @@ -38,12 +38,12 @@ fn queue_peek_front_test() { queue.enqueue(3); match queue.peek_front() { - Option::Some(result) => { assert_eq!(*(result.unbox()), 1, "wrong result"); }, + Option::Some(result) => { assert_eq!(*(result.unbox()), 1); }, Option::None => { assert!(false, "should return value"); }, }; let result_len = queue.len(); - assert_eq!(result_len, 3, "should not remove items"); + assert_eq!(result_len, 3); } #[test] @@ -55,10 +55,10 @@ fn queue_dequeue_test() { queue.enqueue(3); match queue.dequeue() { - Option::Some(result) => { assert_eq!(result, 1, "wrong result"); }, + Option::Some(result) => { assert_eq!(result, 1); }, Option::None => { assert!(false, "should return a value"); }, }; let result_len = queue.len(); - assert_eq!(result_len, 2, "should remove item"); + assert_eq!(result_len, 2); } diff --git a/packages/data_structures/src/tests/stack.cairo b/packages/data_structures/src/tests/stack.cairo index 0fb94a88..fefcf71c 100644 --- a/packages/data_structures/src/tests/stack.cairo +++ b/packages/data_structures/src/tests/stack.cairo @@ -2,15 +2,15 @@ use alexandria_data_structures::stack::{StackTrait, Felt252Stack, NullableStack}; -fn stack_new_test>(stack: @S) { +fn stack_new_test>(stack: @S) { assert!(stack.len() == 0, "stack length should be 0"); } -fn stack_is_empty_test>(stack: @S) { +fn stack_is_empty_test>(stack: @S) { assert!(stack.is_empty(), "stack should be empty"); } -fn stack_push_test, +Drop, impl SDestruct: Destruct>( +fn stack_push_test, +Drop, +Destruct>( ref stack: S, val_1: T, val_2: T ) { stack.push(val_1); @@ -20,15 +20,7 @@ fn stack_push_test, +Drop, impl SDestruct: assert!(stack.len() == 2, "len should be 2"); } -fn stack_peek_test< - S, - T, - impl Stack: StackTrait, - +Drop, - +Copy, - +PartialEq, - impl SDestruct: Destruct ->( +fn stack_peek_test, +Drop, +Copy, +PartialEq, +Destruct>( ref stack: S, val_1: T, val_2: T ) { stack.push(val_1); @@ -41,15 +33,7 @@ fn stack_peek_test< assert!(stack.len() == 2, "should not remove items"); } -fn stack_pop_test< - S, - T, - impl Stack: StackTrait, - +Drop, - +Copy, - +PartialEq, - impl SDestruct: Destruct ->( +fn stack_pop_test, +Drop, +Copy, +PartialEq, +Destruct>( ref stack: S, val_1: T, val_2: T ) { stack.push(val_1); @@ -65,13 +49,7 @@ fn stack_pop_test< } fn stack_push_pop_push_test< - S, - T, - impl Stack: StackTrait, - +Drop, - +Copy, - +PartialEq, - impl SDestruct: Destruct + S, T, +StackTrait, +Drop, +Copy, +PartialEq, +Destruct >( ref stack: S, val_1: T, val_2: T, val_3: T ) { diff --git a/packages/data_structures/src/tests/vec.cairo b/packages/data_structures/src/tests/vec.cairo index 59ab35a3..a57b1258 100644 --- a/packages/data_structures/src/tests/vec.cairo +++ b/packages/data_structures/src/tests/vec.cairo @@ -1,22 +1,19 @@ // Internal imports use alexandria_data_structures::vec::{Felt252Vec, NullableVec, VecTrait}; +use core::ops::index::Index; -fn vec_new_test>(vec: @V) { +fn vec_new_test>(vec: @V) { assert!(vec.len() == 0, "vec length should be 0"); } -fn vec_len_test< - V, T, impl Vec: VecTrait, +Drop, +Copy, +PartialEq, impl SDestruct: Destruct ->( +fn vec_len_test, +Drop, +Copy, +PartialEq, +Destruct>( ref vec: V, val_1: T ) { vec.push(val_1); assert!(vec.len() == 1, "vec length should be 1"); } -fn vec_get_test< - V, T, impl Vec: VecTrait, +Drop, +Copy, +PartialEq, impl SDestruct: Destruct ->( +fn vec_get_test, +Drop, +Copy, +PartialEq, +Destruct>( ref vec: V, val_1: T ) { vec.push(val_1); @@ -24,9 +21,7 @@ fn vec_get_test< assert!(vec.get(1).is_none(), "vec get should return none"); } -fn vec_at_test< - V, T, impl Vec: VecTrait, +Drop, +Copy, +PartialEq, impl SDestruct: Destruct ->( +fn vec_at_test, +Drop, +Copy, +PartialEq, +Destruct>( ref vec: V, val_1: T ) { vec.push(val_1); @@ -34,16 +29,14 @@ fn vec_at_test< } fn vec_at_out_of_bounds_test< - V, T, impl Vec: VecTrait, +Drop, +Copy, +PartialEq, impl SDestruct: Destruct + V, T, +VecTrait, +Drop, +Copy, +PartialEq, +Destruct >( ref vec: V ) { vec.at(0); } -fn vec_push_test< - V, T, impl Vec: VecTrait, +Drop, +Copy, +PartialEq, impl SDestruct: Destruct ->( +fn vec_push_test, +Drop, +Copy, +PartialEq, +Destruct>( ref vec: V, val_1: T ) { vec.push(val_1); @@ -51,9 +44,7 @@ fn vec_push_test< assert!(vec.at(0) == val_1, "vec get should return val_1"); } -fn vec_set_test< - V, T, impl Vec: VecTrait, +Drop, +Copy, +PartialEq, impl SDestruct: Destruct ->( +fn vec_set_test, +Drop, +Copy, +PartialEq, +Destruct>( ref vec: V, val_1: T, val_2: T ) { vec.push(val_1); @@ -63,7 +54,7 @@ fn vec_set_test< } fn vec_set_test_expect_error< - V, T, impl Vec: VecTrait, +Drop, +Copy, +PartialEq, impl SDestruct: Destruct + V, T, +VecTrait, +Drop, +Copy, +PartialEq, +Destruct >( ref vec: V, val_1: T, val_2: T ) { @@ -74,30 +65,33 @@ fn vec_set_test_expect_error< fn vec_index_trait_test< V, T, - impl Vec: VecTrait, + +VecTrait, + impl IndexImpl: Index, +Drop, +Copy, +PartialEq, - impl SDestruct: Destruct, - impl VIndex: Index + +Destruct, + +Into >( ref vec: V, val_1: T, val_2: T ) { vec.push(val_1); vec.push(val_2); - assert!(vec[0] == val_1, "vec[0] != val_1"); - assert!(vec[1] == val_2, "vec[1] != val_2"); + assert!(vec[0].into() == val_1, "vec[0] != val_1"); + assert!(vec[1].into() == val_2, "vec[1] != val_2"); } fn vec_index_trait_out_of_bounds_test< V, T, - impl Vec: VecTrait, + +VecTrait, + impl IndexImpl: Index, +Drop, +Copy, + +Drop, + +Copy, +PartialEq, - impl SDestruct: Destruct, - impl VIndex: Index + +Destruct, >( ref vec: V, val_1: T ) { diff --git a/packages/data_structures/src/vec.cairo b/packages/data_structures/src/vec.cairo index e2a8e0b9..60ab2ab2 100644 --- a/packages/data_structures/src/vec.cairo +++ b/packages/data_structures/src/vec.cairo @@ -1,5 +1,7 @@ -use core::integer::u32_wrapping_add; use core::nullable::NullableImpl; +use core::num::traits::WrappingAdd; +use core::ops::index::Index; + //! Vec implementation. //! //! # Example @@ -40,7 +42,7 @@ pub trait VecTrait { /// Parameters /// * self The vec instance. /// * value The value to push onto the vec. - fn push(ref self: V, value: T) -> (); + fn push(ref self: V, value: T); /// Sets the item at the given index to the given value. /// Panics if the index is out of bounds. @@ -58,7 +60,9 @@ pub trait VecTrait { fn len(self: @V) -> usize; } -impl VecIndex> of Index { +impl VecIndex> of Index { + type Target = T; + #[inline(always)] fn index(ref self: V, index: usize) -> T { self.at(index) @@ -97,9 +101,9 @@ impl Felt252VecImpl, +Copy, +Felt252DictValue> of VecTrait, value: T) -> () { + fn push(ref self: Felt252Vec, value: T) { self.items.insert(self.len.into(), value); - self.len = u32_wrapping_add(self.len, 1_usize); + self.len = self.len.wrapping_add(1); } fn set(ref self: Felt252Vec, index: usize, value: T) { @@ -141,9 +145,9 @@ impl NullableVecImpl, +Copy> of VecTrait, T> { self.items.get(index.into()).deref() } - fn push(ref self: NullableVec, value: T) -> () { + fn push(ref self: NullableVec, value: T) { self.items.insert(self.len.into(), NullableImpl::new(value)); - self.len = u32_wrapping_add(self.len, 1_usize); + self.len = self.len.wrapping_add(1); } fn set(ref self: NullableVec, index: usize, value: T) { diff --git a/packages/encoding/Scarb.toml b/packages/encoding/Scarb.toml index a20ca187..82c57476 100644 --- a/packages/encoding/Scarb.toml +++ b/packages/encoding/Scarb.toml @@ -12,3 +12,6 @@ fmt.workspace = true alexandria_math = { path = "../math" } alexandria_numeric = { path = "../numeric" } alexandria_bytes = { path = "../bytes" } + +[dev-dependencies] +cairo_test.workspace = true \ No newline at end of file diff --git a/packages/encoding/src/base64.cairo b/packages/encoding/src/base64.cairo index d2ed960f..f6d6b2d1 100644 --- a/packages/encoding/src/base64.cairo +++ b/packages/encoding/src/base64.cairo @@ -1,6 +1,6 @@ use alexandria_data_structures::array_ext::ArrayTraitExt; use alexandria_math::BitShift; -use core::integer::BoundedInt; +use core::num::traits::Bounded; pub trait Encoder { fn encode(data: T) -> Array; @@ -101,7 +101,7 @@ pub fn encode_felt(self: felt252, base64_chars: Span) -> Array { let mut num: u256 = self.into(); if num != 0 { let (quotient, remainder) = DivRem::div_rem(num, 65536_u256.try_into().unwrap()); - // Safe since 'remainder' is always less than 65536 (2^16), + // Safe since 'remainder' is always less than 65536 (2^16), // which is within the range of usize (less than 2^32). let remainder: usize = remainder.try_into().unwrap(); let r3 = (remainder / 1024) & 63; @@ -114,7 +114,7 @@ pub fn encode_felt(self: felt252, base64_chars: Span) -> Array { } while (num != 0) { let (quotient, remainder) = DivRem::div_rem(num, 16777216_u256.try_into().unwrap()); - // Safe since 'remainder' is always less than 16777216 (2^24), + // Safe since 'remainder' is always less than 16777216 (2^24), // which is within the range of usize (less than 2^32). let remainder: usize = remainder.try_into().unwrap(); let r4 = remainder / 262144; @@ -172,15 +172,15 @@ fn decode_loop(p: u8, data: Array, d: usize, ref result: Array) { | BitShift::shl((get_base64_value(*data[d + 2])).into(), 6) | (get_base64_value(*data[d + 3])).into(); - let mut i: u8 = (BitShift::shr(x, 16) & BoundedInt::::max().into()).try_into().unwrap(); + let mut i: u8 = (BitShift::shr(x, 16) & Bounded::::MAX.into()).try_into().unwrap(); result.append(i); - i = (BitShift::shr(x, 8) & BoundedInt::::max().into()).try_into().unwrap(); + i = (BitShift::shr(x, 8) & Bounded::::MAX.into()).try_into().unwrap(); if d + 4 >= data.len() && p == 2 { return; } result.append(i); - i = (x & BoundedInt::::max().into()).try_into().unwrap(); + i = (x & Bounded::::MAX.into()).try_into().unwrap(); if d + 4 >= data.len() && p == 1 { return; } diff --git a/packages/encoding/src/reversible.cairo b/packages/encoding/src/reversible.cairo index 06ce717d..1116fc64 100644 --- a/packages/encoding/src/reversible.cairo +++ b/packages/encoding/src/reversible.cairo @@ -1,5 +1,6 @@ use core::integer::u512; use core::num::traits::Zero; +use core::ops::{MulAssign, AddAssign}; const SELECT_BYTE: u16 = 0x100; const SELECT_BIT: u8 = 0b10; @@ -30,9 +31,9 @@ pub fn reversing< +TryInto>, +DivRem, +Drop, - +MulEq, + +MulAssign, +Rem, - +AddEq + +AddAssign >( word: T, size: usize, step: T ) -> (T, T) { @@ -42,7 +43,14 @@ pub fn reversing< #[inline] pub fn reversing_partial_result< - T, +Copy, +DivRem, +TryInto>, +Drop, +MulEq, +Rem, +AddEq + T, + +Copy, + +DivRem, + +TryInto>, + +Drop, + +MulAssign, + +Rem, + +AddAssign >( mut word: T, mut onto: T, size: usize, step: T ) -> (T, T) { diff --git a/packages/encoding/src/rlp.cairo b/packages/encoding/src/rlp.cairo index bdb3cb9d..88a3adc1 100644 --- a/packages/encoding/src/rlp.cairo +++ b/packages/encoding/src/rlp.cairo @@ -88,14 +88,12 @@ pub impl RLPImpl of RLPTrait { let item = input.pop_front().unwrap(); match item { - RLPItem::String(string) => { - output.extend_from_span(RLPTrait::encode_string(*string)?); - }, + RLPItem::String(string) => { output.extend_from_span(Self::encode_string(*string)?); }, RLPItem::List(list) => { if (*list).len() == 0 { output.append(0xc0); } else { - let payload = RLPTrait::encode(*list)?; + let payload = Self::encode(*list)?; let payload_len = payload.len(); if payload_len > 55 { let len_in_bytes = payload_len.to_bytes(); @@ -113,7 +111,7 @@ pub impl RLPImpl of RLPTrait { } if input.len() > 0 { - output.extend_from_span(RLPTrait::encode(input)?); + output.extend_from_span(Self::encode(input)?); } Result::Ok(output.span()) @@ -163,7 +161,7 @@ pub impl RLPImpl of RLPTrait { let mut output: Array = Default::default(); let input_len = input.len(); - let (rlp_type, offset, len) = RLPTrait::decode_type(input)?; + let (rlp_type, offset, len) = Self::decode_type(input)?; if input_len < offset + len { return Result::Err(RLPError::InputTooShort); @@ -179,7 +177,7 @@ pub impl RLPImpl of RLPTrait { }, RLPType::List => { if len > 0 { - let res = RLPTrait::decode(input.slice(offset, len))?; + let res = Self::decode(input.slice(offset, len))?; output.append(RLPItem::List(res)); } else { output.append(RLPItem::List(array![].span())); @@ -191,7 +189,7 @@ pub impl RLPImpl of RLPTrait { if total_item_len < input_len { output .extend_from_span( - RLPTrait::decode(input.slice(total_item_len, input_len - total_item_len))? + Self::decode(input.slice(total_item_len, input_len - total_item_len))? ); } diff --git a/packages/encoding/src/tests/base64_felt_test.cairo b/packages/encoding/src/tests/base64_felt_test.cairo index bb566663..9d64a92a 100644 --- a/packages/encoding/src/tests/base64_felt_test.cairo +++ b/packages/encoding/src/tests/base64_felt_test.cairo @@ -26,7 +26,7 @@ fn base64encode_empty_test() { let input = 0; let result = Base64FeltEncoder::encode(input); let check = Base64Encoder::encode(bytes_be(input)); - assert_eq!(result, check, "Expected equal"); + assert_eq!(result, check); } #[test] @@ -35,7 +35,7 @@ fn base64encode_simple_test() { let input = 'a'; let result = Base64FeltEncoder::encode(input); let check = Base64Encoder::encode(bytes_be(input)); - assert_eq!(result, check, "Expected equal"); + assert_eq!(result, check); } #[test] @@ -44,7 +44,7 @@ fn base64encode_hello_world_test() { let input = 'hello world'; let result = Base64FeltEncoder::encode(input); let check = Base64Encoder::encode(bytes_be(input)); - assert_eq!(result, check, "Expected equal"); + assert_eq!(result, check); } @@ -55,7 +55,7 @@ fn base64encode_with_plus_and_slash() { let result = Base64FeltEncoder::encode(input); let check = Base64Encoder::encode(bytes_be(input)); - assert_eq!(result, check, "Expected equal"); + assert_eq!(result, check); } #[test] @@ -65,5 +65,5 @@ fn base64urlencode_with_plus_and_slash() { let result = Base64UrlFeltEncoder::encode(input); let check = Base64UrlEncoder::encode(bytes_be(input)); - assert_eq!(result, check, "Expected equal"); + assert_eq!(result, check); } diff --git a/packages/encoding/src/tests/base64_test.cairo b/packages/encoding/src/tests/base64_test.cairo index 5b1be4fb..34e16f75 100644 --- a/packages/encoding/src/tests/base64_test.cairo +++ b/packages/encoding/src/tests/base64_test.cairo @@ -5,7 +5,7 @@ use alexandria_encoding::base64::{Base64Encoder, Base64Decoder, Base64UrlEncoder fn base64encode_empty_test() { let input = array![]; let result = Base64Encoder::encode(input); - assert_eq!(result.len(), 0, "invalid result length"); + assert_eq!(result.len(), 0); } #[test] @@ -14,11 +14,11 @@ fn base64encode_simple_test() { let input = array!['a']; let result = Base64Encoder::encode(input); - assert_eq!(result.len(), 4, "invalid result length"); - assert_eq!(*result[0], 'Y', "invalid result[0]"); - assert_eq!(*result[1], 'Q', "invalid result[1]"); - assert_eq!(*result[2], '=', "invalid result[2]"); - assert_eq!(*result[3], '=', "invalid result[3]"); + assert_eq!(result.len(), 4); + assert_eq!(*result[0], 'Y'); + assert_eq!(*result[1], 'Q'); + assert_eq!(*result[2], '='); + assert_eq!(*result[3], '='); } #[test] @@ -27,23 +27,23 @@ fn base64encode_hello_world_test() { let input = array!['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']; let result = Base64Encoder::encode(input); - assert_eq!(result.len(), 16, "invalid result length"); - assert_eq!(*result[0], 'a', "invalid result[0]"); - assert_eq!(*result[1], 'G', "invalid result[1]"); - assert_eq!(*result[2], 'V', "invalid result[2]"); - assert_eq!(*result[3], 's', "invalid result[3]"); - assert_eq!(*result[4], 'b', "invalid result[4]"); - assert_eq!(*result[5], 'G', "invalid result[5]"); - assert_eq!(*result[6], '8', "invalid result[6]"); - assert_eq!(*result[7], 'g', "invalid result[7]"); - assert_eq!(*result[8], 'd', "invalid result[8]"); - assert_eq!(*result[9], '2', "invalid result[9]"); - assert_eq!(*result[10], '9', "invalid result[10]"); - assert_eq!(*result[11], 'y', "invalid result[11]"); - assert_eq!(*result[12], 'b', "invalid result[12]"); - assert_eq!(*result[13], 'G', "invalid result[13]"); - assert_eq!(*result[14], 'Q', "invalid result[14]"); - assert_eq!(*result[15], '=', "invalid result[15]"); + assert_eq!(result.len(), 16); + assert_eq!(*result[0], 'a'); + assert_eq!(*result[1], 'G'); + assert_eq!(*result[2], 'V'); + assert_eq!(*result[3], 's'); + assert_eq!(*result[4], 'b'); + assert_eq!(*result[5], 'G'); + assert_eq!(*result[6], '8'); + assert_eq!(*result[7], 'g'); + assert_eq!(*result[8], 'd'); + assert_eq!(*result[9], '2'); + assert_eq!(*result[10], '9'); + assert_eq!(*result[11], 'y'); + assert_eq!(*result[12], 'b'); + assert_eq!(*result[13], 'G'); + assert_eq!(*result[14], 'Q'); + assert_eq!(*result[15], '='); } #[test] @@ -52,7 +52,7 @@ fn base64decode_empty_test() { let input = array![]; let result = Base64Decoder::decode(input); - assert_eq!(result.len(), 0, "invalid result length"); + assert_eq!(result.len(), 0); } #[test] @@ -61,8 +61,8 @@ fn base64decode_simple_test() { let input = array!['Y', 'Q', '=', '=']; let result = Base64Decoder::decode(input); - assert_eq!(result.len(), 1, "invalid result length"); - assert_eq!(*result[0], 'a', "invalid result[0]"); + assert_eq!(result.len(), 1); + assert_eq!(*result[0], 'a'); } #[test] @@ -73,18 +73,18 @@ fn base64decode_hello_world_test() { ]; let result = Base64Decoder::decode(input); - assert_eq!(result.len(), 11, "invalid result length"); - assert_eq!(*result[0], 'h', "invalid result[0]"); - assert_eq!(*result[1], 'e', "invalid result[1]"); - assert_eq!(*result[2], 'l', "invalid result[2]"); - assert_eq!(*result[3], 'l', "invalid result[3]"); - assert_eq!(*result[4], 'o', "invalid result[4]"); - assert_eq!(*result[5], ' ', "invalid result[5]"); - assert_eq!(*result[6], 'w', "invalid result[6]"); - assert_eq!(*result[7], 'o', "invalid result[7]"); - assert_eq!(*result[8], 'r', "invalid result[8]"); - assert_eq!(*result[9], 'l', "invalid result[9]"); - assert_eq!(*result[10], 'd', "invalid result[10]"); + assert_eq!(result.len(), 11); + assert_eq!(*result[0], 'h'); + assert_eq!(*result[1], 'e'); + assert_eq!(*result[2], 'l'); + assert_eq!(*result[3], 'l'); + assert_eq!(*result[4], 'o'); + assert_eq!(*result[5], ' '); + assert_eq!(*result[6], 'w'); + assert_eq!(*result[7], 'o'); + assert_eq!(*result[8], 'r'); + assert_eq!(*result[9], 'l'); + assert_eq!(*result[10], 'd'); } #[test] @@ -93,11 +93,11 @@ fn base64encode_with_plus_and_slash() { let input = array![255, 239]; let result = Base64Encoder::encode(input); - assert_eq!(result.len(), 4, "invalid result length"); - assert_eq!(*result[0], '/', "invalid result[0]"); - assert_eq!(*result[1], '+', "invalid result[1]"); - assert_eq!(*result[2], '8', "invalid result[2]"); - assert_eq!(*result[3], '=', "invalid result[3]"); + assert_eq!(result.len(), 4); + assert_eq!(*result[0], '/'); + assert_eq!(*result[1], '+'); + assert_eq!(*result[2], '8'); + assert_eq!(*result[3], '='); } #[test] @@ -106,11 +106,11 @@ fn base64urlencode_with_plus_and_slash() { let input = array![255, 239]; let result = Base64UrlEncoder::encode(input); - assert_eq!(result.len(), 4, "invalid result length"); - assert_eq!(*result[0], '_', "invalid result[0]"); - assert_eq!(*result[1], '-', "invalid result[1]"); - assert_eq!(*result[2], '8', "invalid result[2]"); - assert_eq!(*result[3], '=', "invalid result[3]"); + assert_eq!(result.len(), 4); + assert_eq!(*result[0], '_'); + assert_eq!(*result[1], '-'); + assert_eq!(*result[2], '8'); + assert_eq!(*result[3], '='); } #[test] @@ -119,9 +119,9 @@ fn base64decode_with_plus_and_slash() { let input = array!['/', '+', '8', '=']; let result = Base64UrlDecoder::decode(input); - assert_eq!(result.len(), 2, "invalid result length"); - assert_eq!(*result[0], 255, "invalid result[0]"); - assert_eq!(*result[1], 239, "invalid result[1]"); + assert_eq!(result.len(), 2); + assert_eq!(*result[0], 255); + assert_eq!(*result[1], 239); } #[test] @@ -130,7 +130,7 @@ fn base64urldecode_with_plus_and_slash() { let input = array!['_', '-', '8', '=']; let result = Base64UrlDecoder::decode(input); - assert_eq!(result.len(), 2, "invalid result length"); - assert_eq!(*result[0], 255, "invalid result[0]"); - assert_eq!(*result[1], 239, "invalid result[1]"); + assert_eq!(result.len(), 2); + assert_eq!(*result[0], 255); + assert_eq!(*result[1], 239); } diff --git a/packages/encoding/src/tests/reversible_test.cairo b/packages/encoding/src/tests/reversible_test.cairo index b919f553..0618b4c7 100644 --- a/packages/encoding/src/tests/reversible_test.cairo +++ b/packages/encoding/src/tests/reversible_test.cairo @@ -53,7 +53,7 @@ fn test_reverse_bytes_u256() { let t2: u128 = 0x202122232425262728292a2b2c2d2e2f; let t = u256 { low: t1, high: t2 }; let rev = t.reverse_bytes(); - assert!(rev == u256 { low: t2.reverse_bytes(), high: t1.reverse_bytes() }, "not equal"); + assert!(rev == u256 { low: t2.reverse_bytes(), high: t1.reverse_bytes() }); assert!(rev.reverse_bytes() == t, "not equal"); } diff --git a/packages/encoding/src/tests/sol_abi.cairo b/packages/encoding/src/tests/sol_abi.cairo index 39354a5f..e3f2d278 100644 --- a/packages/encoding/src/tests/sol_abi.cairo +++ b/packages/encoding/src/tests/sol_abi.cairo @@ -14,15 +14,14 @@ fn compare_bytes(actual: @Bytes, expected: @Bytes) -> bool { return false; } let mut i: usize = 0; - while i < actual - .size() { - let (_, actual_val) = actual.read_u8(i); - let (_, expected_val) = expected.read_u8(i); - if actual_val != expected_val { - break; - } - i += 1; - }; + while i < actual.size() { + let (_, actual_val) = actual.read_u8(i); + let (_, expected_val) = expected.read_u8(i); + if actual_val != expected_val { + break; + } + i += 1; + }; if i < actual.size() { return false; } @@ -89,7 +88,7 @@ fn encode_test() { .encode(sba) .encode(address) .encode(eth_address); - assert_eq!(encoded, expected, "Encode uints failed"); + assert_eq!(encoded, expected); } #[test] @@ -135,7 +134,7 @@ fn encode_packed_test() { .encode_packed(address) .encode_packed(eth_address) .encode_packed(bytesArray); - assert_eq!(encoded, expected, "Encode packed uints failed"); + assert_eq!(encoded, expected); } #[test] @@ -148,7 +147,7 @@ fn encoded_as_test() { .encode_as(3, 0x101112_u128) .encode_as(21, 0xaabbcc_felt252) .encode_as(5, 0xa0b1c2_u256); - assert_eq!(encoded, expected, "Encode as failed"); + assert_eq!(encoded, expected); let sba: ByteArray = SolBytesTrait::bytes10(0x0000a0b1c2c3c4c5c6c8).into(); let bytes_31: bytes31 = 0xaabbcc.try_into().unwrap(); @@ -157,16 +156,16 @@ fn encoded_as_test() { .encode_as(3, SolBytesTrait::bytes10(0x10111213141516171910)) .encode_as(21, bytes_31) .encode_as(5, sba); - assert_eq!(encoded, expected, "Encode as from bytes failed"); + assert_eq!(encoded, expected); } #[test] fn selector_test() { - // selector for : transfer(address,uint256) + // selector for : transfer(address,uint256) let expected: Bytes = BytesTrait::new(4, array![0xa9059cbb000000000000000000000000]); let mut encoded: Bytes = BytesTrait::new_empty(); encoded = encoded.encode_selector(0xa9059cbb_u32); - assert_eq!(encoded, expected, "Encode selector failed"); + assert_eq!(encoded, expected); // encode call : transfer(0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF, 10000) let expected: Bytes = BytesTrait::new( @@ -182,7 +181,7 @@ fn selector_test() { let mut encoded: Bytes = BytesTrait::new_empty(); let eth_address: EthAddress = 0xDeaDbeefdEAdbeefdEadbEEFdeadbeEFdEaDbeeF_u256.into(); encoded = encoded.encode_selector(0xa9059cbb_u32).encode(eth_address).encode(10000_u256); - assert_eq!(encoded, expected, "Encode selector full failed"); + assert_eq!(encoded, expected); } #[test] @@ -219,20 +218,20 @@ fn decode_test() { let mut offset = 0; let decoded: u16 = encoded.decode(ref offset); - assert_eq!(decoded, 0xa0a1, "Decode uint16 failed"); - assert_eq!(offset, 32, "Offset after decode uint16 failed"); + assert_eq!(decoded, 0xa0a1); + assert_eq!(offset, 32); let decoded: u32 = encoded.decode(ref offset); - assert_eq!(decoded, 0xa2a3a4a5, "Decode uint32 failed"); - assert_eq!(offset, 64, "Offset after decode uint32 failed"); + assert_eq!(decoded, 0xa2a3a4a5); + assert_eq!(offset, 64); let decoded: u8 = encoded.decode(ref offset); - assert_eq!(decoded, 0xa6, "Decode uint8 failed"); - assert_eq!(offset, 96, "Offset after decode uint8 failed"); + assert_eq!(decoded, 0xa6); + assert_eq!(offset, 96); let decoded: u128 = encoded.decode(ref offset); - assert_eq!(decoded, 0xa7a8a9aaabacadaeafb0b1b2b3b4b5b6, "Decode uint128 failed"); - assert_eq!(offset, 128, "Offset after decode uint128 failed"); + assert_eq!(decoded, 0xa7a8a9aaabacadaeafb0b1b2b3b4b5b6); + assert_eq!(offset, 128); let decoded: u256 = encoded.decode(ref offset); assert_eq!( @@ -240,45 +239,45 @@ fn decode_test() { 0xabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcdefabcd_u256, "Decode uint256 failed" ); - assert_eq!(offset, 160, "Offset after decode uint256 failed"); + assert_eq!(offset, 160); let decoded: u64 = encoded.decode(ref offset); - assert_eq!(decoded, 0xb7b8b9babbbcbdbe, "Decode uint64 failed"); - assert_eq!(offset, 192, "Offset after decode uint64 failed"); + assert_eq!(decoded, 0xb7b8b9babbbcbdbe); + assert_eq!(offset, 192); let decoded: Bytes = SolBytesTrait::::bytes5(encoded.decode(ref offset)); - assert_eq!(decoded, SolBytesTrait::bytes5(0xa0a1a2a3), "Decode Bytes failed"); - assert_eq!(offset, 224, "Offset after decode Bytes failed"); + assert_eq!(decoded, SolBytesTrait::bytes5(0xa0a1a2a3)); + assert_eq!(offset, 224); let decoded: ByteArray = encoded.decode(ref offset); let expected: ByteArray = SolBytesTrait::bytes32( 0xa0a1a2a3a4a5a6a7a8a9aaabacadaeafb0b1b2b3000000000000000000000000_u256 ) .into(); - assert_eq!(decoded, expected, "Decode ByteArray failed"); - assert_eq!(offset, 256, "Offset after decode ByteArray failed"); + assert_eq!(decoded, expected); + assert_eq!(offset, 256); let decoded: bytes31 = encoded.decode(ref offset); let bytes_31: bytes31 = 0xa0aaab00000000000000000000000000ac.try_into().unwrap(); assert!(decoded == bytes_31, "Decode byte31 failed"); - assert_eq!(offset, 288, "Offset after decode byte31 failed"); + assert_eq!(offset, 288); let decoded: felt252 = encoded.decode(ref offset); - assert_eq!(decoded, 0x1234_felt252, "Decode felt252 failed"); - assert_eq!(offset, 320, "Offset after decode felt252 failed"); + assert_eq!(decoded, 0x1234_felt252); + assert_eq!(offset, 320); let expected: ContractAddress = 0xa0a1a2a3000000000000000000000000000000000000000000000000001234_felt252 .try_into() .expect('Couldn\'t convert to address'); let decoded: ContractAddress = encoded.decode(ref offset); - assert_eq!(decoded, expected, "Decode ContractAddress failed"); - assert_eq!(offset, 352, "Offset after decode ContractAddress failed"); + assert_eq!(decoded, expected); + assert_eq!(offset, 352); let expected: EthAddress = 0xDeadbeefDeaDbeefdEAdbeefdEadbEEFdeadbeEF_u256.into(); let decoded: EthAddress = encoded.decode(ref offset); - assert_eq!(decoded, expected, "Decode EthAddress failed"); - assert_eq!(offset, 384, "Offset after decode EthAddress failed"); + assert_eq!(decoded, expected); + assert_eq!(offset, 384); } #[test] @@ -290,7 +289,7 @@ fn sol_bytes_test() { let mut bytesValAcc: Bytes = BytesTrait::new_empty(); bytesValAcc.concat(@bytesVal5); bytesValAcc.concat(@bytesVal9); - assert_eq!(expectedVal14, bytesValAcc, "Concat bytes ints failed"); + assert_eq!(expectedVal14, bytesValAcc); // Test bytesX with integer types needing `into` calls let expectedVal21: Bytes = SolBytesTrait::bytes21( @@ -301,7 +300,7 @@ fn sol_bytes_test() { let mut bytesValAcc: Bytes = BytesTrait::new_empty(); bytesValAcc.concat(@bytesVal18); bytesValAcc.concat(@bytesVal3); - assert_eq!(expectedVal21, bytesValAcc, "Concat bytes ints into failed"); + assert_eq!(expectedVal21, bytesValAcc); // Test bytesX with Bytes types let expectedVal25: Bytes = SolBytesTrait::bytes25( @@ -318,5 +317,5 @@ fn sol_bytes_test() { let mut bytesValAcc: Bytes = BytesTrait::new_empty(); bytesValAcc.concat(@bytesVal6); bytesValAcc.concat(@bytesVal19); - assert_eq!(expectedVal25, bytesValAcc, "Concat bytes failed"); + assert_eq!(expectedVal25, bytesValAcc); } diff --git a/packages/linalg/Scarb.toml b/packages/linalg/Scarb.toml index 2ca95fdb..24697711 100644 --- a/packages/linalg/Scarb.toml +++ b/packages/linalg/Scarb.toml @@ -10,3 +10,6 @@ fmt.workspace = true [dependencies] alexandria_math = { path = "../math" } + +[dev-dependencies] +cairo_test.workspace = true \ No newline at end of file diff --git a/packages/linalg/src/dot.cairo b/packages/linalg/src/dot.cairo index f388299b..7257f689 100644 --- a/packages/linalg/src/dot.cairo +++ b/packages/linalg/src/dot.cairo @@ -1,4 +1,5 @@ use core::num::traits::Zero; +use core::ops::AddAssign; //! Dot product of two arrays /// Compute the dot product for 2 given arrays. @@ -7,7 +8,7 @@ use core::num::traits::Zero; /// * `ys` - The second sequence of len L. /// # Returns /// * `sum` - The dot product. -pub fn dot, +AddEq, +Zero, +Copy, +Drop,>( +pub fn dot, +AddAssign, +Zero, +Copy, +Drop,>( mut xs: Span, mut ys: Span ) -> T { // [Check] Inputs @@ -15,11 +16,10 @@ pub fn dot, +AddEq, +Zero, +Copy, +Drop,>( // [Compute] Dot product in a loop let mut sum = Zero::zero(); - while !xs - .is_empty() { - let x = *xs.pop_front().unwrap(); - let y = *ys.pop_front().unwrap(); - sum += x * y; - }; + while !xs.is_empty() { + let x = *xs.pop_front().unwrap(); + let y = *ys.pop_front().unwrap(); + sum += x * y; + }; sum } diff --git a/packages/linalg/src/kron.cairo b/packages/linalg/src/kron.cairo index d74d6d90..89aae78e 100644 --- a/packages/linalg/src/kron.cairo +++ b/packages/linalg/src/kron.cairo @@ -22,14 +22,12 @@ pub fn kron, +Copy, +Drop,>( // [Compute] Kronecker product in a loop let mut array = array![]; - while let Option::Some(x_value) = xs - .pop_front() { - let mut ys_clone = ys; - while let Option::Some(y_value) = ys_clone - .pop_front() { - array.append(*x_value * *y_value); - } - }; + for x_value in xs { + let ys_clone = ys; + for y_value in ys_clone { + array.append(*x_value * *y_value); + } + }; Result::Ok(array) } diff --git a/packages/linalg/src/norm.cairo b/packages/linalg/src/norm.cairo index 6401347d..dee80fff 100644 --- a/packages/linalg/src/norm.cairo +++ b/packages/linalg/src/norm.cairo @@ -14,16 +14,15 @@ pub fn norm, +Zero, +Copy, +Drop>( mut xs: Span, ord: u128, iter: usize ) -> u128 { let mut norm: u128 = 0; - while let Option::Some(x_value) = xs - .pop_front() { - if ord == 0 { - if (*x_value).is_non_zero() { - norm += 1; - } - } else { - norm += pow((*x_value).into(), ord); - }; + for x_value in xs { + if ord == 0 { + if (*x_value).is_non_zero() { + norm += 1; + } + } else { + norm += pow((*x_value).into(), ord); }; + }; if ord == 0 { return norm; diff --git a/packages/linalg/src/tests/dot_test.cairo b/packages/linalg/src/tests/dot_test.cairo index e97106a5..fff011d8 100644 --- a/packages/linalg/src/tests/dot_test.cairo +++ b/packages/linalg/src/tests/dot_test.cairo @@ -5,7 +5,7 @@ use alexandria_linalg::dot::dot; fn dot_product_test() { let xs = array![3_u64, 5, 7]; let ys = array![11, 13, 17]; - assert_eq!(dot(xs.span(), ys.span()), 217, "invalid dot product"); + assert_eq!(dot(xs.span(), ys.span()), 217); } #[test] diff --git a/packages/linalg/src/tests/kron_test.cairo b/packages/linalg/src/tests/kron_test.cairo index 5b6d9c8d..26be4b66 100644 --- a/packages/linalg/src/tests/kron_test.cairo +++ b/packages/linalg/src/tests/kron_test.cairo @@ -6,15 +6,15 @@ fn kron_product_test() { let xs = array![1_u64, 10, 100]; let ys = array![5, 6, 7]; let zs = kron(xs.span(), ys.span()).unwrap(); - assert_eq!(*zs[0], 5, "wrong value at index 0"); - assert_eq!(*zs[1], 6, "wrong value at index 1"); - assert_eq!(*zs[2], 7, "wrong value at index 2"); - assert_eq!(*zs[3], 50, "wrong value at index 3"); - assert_eq!(*zs[4], 60, "wrong value at index 4"); - assert_eq!(*zs[5], 70, "wrong value at index 5"); - assert_eq!(*zs[6], 500, "wrong value at index 6"); - assert_eq!(*zs[7], 600, "wrong value at index 7"); - assert_eq!(*zs[8], 700, "wrong value at index 8"); + assert_eq!(*zs[0], 5); + assert_eq!(*zs[1], 6); + assert_eq!(*zs[2], 7); + assert_eq!(*zs[3], 50); + assert_eq!(*zs[4], 60); + assert_eq!(*zs[5], 70); + assert_eq!(*zs[6], 500); + assert_eq!(*zs[7], 600); + assert_eq!(*zs[8], 700); } #[test] @@ -22,8 +22,5 @@ fn kron_product_test() { fn kron_product_test_check_len() { let xs = array![1_u64]; let ys = array![]; - assert( - kron(xs.span(), ys.span()) == Result::Err(KronError::UnequalLength), - 'Arrays must have the same len' - ); + assert!(kron(xs.span(), ys.span()) == Result::Err(KronError::UnequalLength)); } diff --git a/packages/linalg/src/tests/norm_test.cairo b/packages/linalg/src/tests/norm_test.cairo index 023ae75d..d432bbf0 100644 --- a/packages/linalg/src/tests/norm_test.cairo +++ b/packages/linalg/src/tests/norm_test.cairo @@ -4,26 +4,26 @@ use alexandria_linalg::norm::norm; #[available_gas(2000000)] fn norm_test_1() { let array = array![3_u128, 4]; - assert_eq!(norm(array.span(), 2, 10), 5, "invalid l2 norm"); + assert_eq!(norm(array.span(), 2, 10), 5); } #[test] #[available_gas(2000000)] fn norm_test_2() { let array = array![3_u128, 4]; - assert_eq!(norm(array.span(), 1, 10), 7, "invalid l1 norm"); + assert_eq!(norm(array.span(), 1, 10), 7); } #[test] #[available_gas(2000000)] fn norm_test_3() { let array = array![3_u128, 4]; - assert_eq!(norm(array.span(), 0, 10), 2, "invalid l1 norm"); + assert_eq!(norm(array.span(), 0, 10), 2); } #[test] #[available_gas(2000000)] fn norm_test_into() { let array = array![3_u32, 4]; - assert_eq!(norm(array.span(), 2, 10), 5, "invalid l2 norm"); + assert_eq!(norm(array.span(), 2, 10), 5); } diff --git a/packages/math/Scarb.toml b/packages/math/Scarb.toml index 797d5bf6..120236be 100644 --- a/packages/math/Scarb.toml +++ b/packages/math/Scarb.toml @@ -11,3 +11,6 @@ fmt.workspace = true [dependencies] # dependency due to ArrayTraitExt::concat in ed25519.cairo alexandria_data_structures = { path = "../data_structures" } + +[dev-dependencies] +cairo_test.workspace = true \ No newline at end of file diff --git a/packages/math/src/bitmap.cairo b/packages/math/src/bitmap.cairo index d47a2071..505b664b 100644 --- a/packages/math/src/bitmap.cairo +++ b/packages/math/src/bitmap.cairo @@ -1,6 +1,7 @@ // Internam imports use alexandria_math::fast_power::fast_power as pow; +use core::ops::DivAssign; #[generate_trait] pub impl Bitmap< @@ -9,7 +10,7 @@ pub impl Bitmap< +Sub, +Mul, +Div, - +DivEq, + +DivAssign, +Rem, +BitAnd, +BitOr, @@ -159,11 +160,12 @@ pub impl Bitmap< /// * `x` - The value for which to compute the most significant bit. /// * `i` - The index for which to start the search. /// # Returns - /// * The index of the nearest left significant bit, None is returned if no significant bit is found. + /// * The index of the nearest left significant bit, None is returned if no significant bit is + /// found. #[inline(always)] fn nearest_left_significant_bit(x: T, i: u8) -> Option:: { let mask = ~(pow(2_u8.into(), i.into()) - 1_u8.into()); - Bitmap::least_significant_bit(x & mask) + Self::least_significant_bit(x & mask) } /// The index of the nearest right significant bit to the index of a number. @@ -171,11 +173,12 @@ pub impl Bitmap< /// * `x` - The value for which to compute the most significant bit. /// * `i` - The index for which to start the search. /// # Returns - /// * The index of the nearest right significant bit, None is returned if no significant bit is found. + /// * The index of the nearest right significant bit, None is returned if no significant bit is + /// found. #[inline(always)] fn nearest_right_significant_bit(x: T, i: u8) -> Option:: { let mask = pow(2_u8.into(), (i + 1).into()) - 1_u8.into(); - Bitmap::most_significant_bit(x & mask) + Self::most_significant_bit(x & mask) } /// The index of the nearest significant bit to the index of a number, @@ -183,13 +186,14 @@ pub impl Bitmap< /// # Arguments /// * `x` - The value for which to compute the most significant bit, must be greater than 0. /// * `i` - The index for which to start the search. - /// * `priority` - if priority is set to true then right is prioritized over left, left over right otherwise. + /// * `priority` - if priority is set to true then right is prioritized over left, left over + /// right otherwise. /// # Returns /// * The index of the nearest significant bit, None is returned if no significant bit is found. #[inline(always)] fn nearest_significant_bit(x: T, i: u8, priority: bool) -> Option:: { - let nlsb = Bitmap::nearest_left_significant_bit(x, i); - let nrsb = Bitmap::nearest_right_significant_bit(x, i); + let nlsb = Self::nearest_left_significant_bit(x, i); + let nrsb = Self::nearest_right_significant_bit(x, i); match (nlsb, nrsb) { ( Option::Some(lhs), Option::Some(rhs) diff --git a/packages/math/src/ed25519.cairo b/packages/math/src/ed25519.cairo index 08cc52ab..5ba9dc6c 100644 --- a/packages/math/src/ed25519.cairo +++ b/packages/math/src/ed25519.cairo @@ -3,10 +3,9 @@ use alexandria_math::mod_arithmetics::{mult_mod, sqr_mod, div_mod, pow_mod, equa use alexandria_math::sha512::{sha512, SHA512_LEN}; use alexandria_math::u512_arithmetics::{u512_add, u512_sub}; use core::array::ArrayTrait; -use core::integer::{ - u512, u512_safe_div_rem_by_u256, u256_wide_mul, u256_overflowing_add, u256_overflow_sub, -}; +use core::integer::{u512, u512_safe_div_rem_by_u256}; use core::math::u256_inv_mod; +use core::num::traits::{OverflowingMul, WideMul}; use core::option::OptionTrait; use core::traits::Div; use core::traits::TryInto; @@ -106,10 +105,10 @@ impl PointDoublingPoint of PointOperations { let x1y1 = mult_mod(x1, y1, prime_nz); let x2y2 = mult_mod(x2, y2, prime_nz); - let y1y2_512 = u256_wide_mul(y1, y2); - let x1x2_512 = u256_wide_mul(x1, x2); - let x1y2_512 = u256_wide_mul(x1, y2); - let y1x2_512 = u256_wide_mul(y1, x2); + let y1y2_512 = WideMul::wide_mul(y1, y2); + let x1x2_512 = WideMul::wide_mul(x1, x2); + let x1y2_512 = WideMul::wide_mul(x1, y2); + let y1x2_512 = WideMul::wide_mul(y1, x2); // y1y2 + ax1x2 = y1y2 - x1x2, a = -1 let (_, y1y2_ax1x2) = u512_safe_div_rem_by_u256( @@ -301,7 +300,8 @@ impl U256TryIntoPoint of TryInto { } } -/// Function that performs point multiplication for an Elliptic Curve point using the double and add method. +/// Function that performs point multiplication for an Elliptic Curve point using the double and add +/// method. /// # Arguments /// * `scalar` - Scalar such that scalar * P = P + P + P + ... + P. /// * `P` - Elliptic Curve point @@ -381,7 +381,8 @@ pub fn verify_signature(msg: Span, signature: Span, pub_key: u256) -> let pub_key_bytes = pub_key_bytes.reversed().span(); let hashable = r_bytes.concat(pub_key_bytes).span().concat(msg); - // k = SHA512(dom2(F, C) -> empty string || R -> half of sig || A -> pub_key || PH(M) -> identity function for msg) + // k = SHA512(dom2(F, C) -> empty string || R -> half of sig || A -> pub_key || PH(M) -> + // identity function for msg) let k: Array = sha512(hashable); let k_u512: u512 = k.span().into(); diff --git a/packages/math/src/extended_euclidean_algorithm.cairo b/packages/math/src/extended_euclidean_algorithm.cairo index 43672931..11d09bd2 100644 --- a/packages/math/src/extended_euclidean_algorithm.cairo +++ b/packages/math/src/extended_euclidean_algorithm.cairo @@ -1,5 +1,5 @@ //! # Extended Euclidean Algorithm. -use core::integer::{u128_overflowing_sub, u128_overflowing_mul, u128_wrapping_sub}; +use core::num::traits::{OverflowingMul, OverflowingSub}; /// Extended Euclidean Algorithm. /// # Arguments @@ -31,8 +31,9 @@ pub fn extended_euclidean_algorithm(a: u128, b: u128) -> (u128, u128, u128) { /// Update the step of the extended Euclidean algorithm. fn update_step(ref a: u128, ref old_a: u128, quotient: u128) { let temp = a; - let (bottom, _) = u128_overflowing_mul(quotient, temp); - a = u128_wrapping_sub(old_a, bottom); + let (bottom, _) = quotient.overflowing_mul(temp); + let (a_tmp, _) = old_a.overflowing_sub(bottom); + a = a_tmp; old_a = temp; } diff --git a/packages/math/src/fast_power.cairo b/packages/math/src/fast_power.cairo index f74e41cd..11329b97 100644 --- a/packages/math/src/fast_power.cairo +++ b/packages/math/src/fast_power.cairo @@ -1,10 +1,11 @@ //! # Fast power algorithm +use core::ops::DivAssign; -/// Calculate the base ^ power +/// Calculate the base ^ power /// using the fast powering algorithm /// # Arguments -/// * ` base ` - The base of the exponentiation -/// * ` power ` - The power of the exponentiation +/// * ` base ` - The base of the exponentiation +/// * ` power ` - The power of the exponentiation /// # Returns /// * ` T ` - The result of base ^ power /// # Panics @@ -12,7 +13,7 @@ pub fn fast_power< T, +Div, - +DivEq, + +DivAssign, +Rem, +Into, +Into, @@ -45,8 +46,8 @@ pub fn fast_power< /// Calculate the ( base ^ power ) mod modulus /// using the fast powering algorithm /// # Arguments -/// * ` base ` - The base of the exponentiation -/// * ` power ` - The power of the exponentiation +/// * ` base ` - The base of the exponentiation +/// * ` power ` - The power of the exponentiation /// * ` modulus ` - The modulus used in the calculation /// # Returns /// * ` T ` - The result of ( base ^ power ) mod modulus @@ -55,7 +56,7 @@ pub fn fast_power< pub fn fast_power_mod< T, +Div, - +DivEq, + +DivAssign, +Rem, +Into, +Into, diff --git a/packages/math/src/fast_root.cairo b/packages/math/src/fast_root.cairo index 689068ba..7d065da0 100644 --- a/packages/math/src/fast_root.cairo +++ b/packages/math/src/fast_root.cairo @@ -1,7 +1,7 @@ //! # Fast root algorithm using the Newton-Raphson method use super::pow; -/// Newton-Raphson optimization to solve the equation x^r = a. +/// Newton-Raphson optimization to solve the equation x^r = a. /// The optimization has a quadratic convergence rate. /// # Arguments /// * ` x ` - The number to calculate the root of diff --git a/packages/math/src/gcd_of_n_numbers.cairo b/packages/math/src/gcd_of_n_numbers.cairo index 0efc779e..3091118b 100644 --- a/packages/math/src/gcd_of_n_numbers.cairo +++ b/packages/math/src/gcd_of_n_numbers.cairo @@ -10,7 +10,7 @@ pub fn gcd(mut n: Span) -> u128 { assert!(!n.is_empty(), "gcd-empty"); let mut a = *n.pop_front().unwrap(); - while let Option::Some(b) = n.pop_front() { + for b in n { a = gcd_two_numbers(a, *b); }; a diff --git a/packages/math/src/i257.cairo b/packages/math/src/i257.cairo index bd95d7f0..694f2cac 100644 --- a/packages/math/src/i257.cairo +++ b/packages/math/src/i257.cairo @@ -1,4 +1,6 @@ use core::num::traits::Zero; +use core::ops::{AddAssign, SubAssign, MulAssign, DivAssign, RemAssign}; + // ====================== INT 257 ====================== // i257 represents a 129-bit integer. @@ -41,13 +43,13 @@ impl i257Add of Add { fn add(lhs: i257, rhs: i257) -> i257 { i257_assert_no_negative_zero(lhs); i257_assert_no_negative_zero(rhs); - // If both integers have the same sign, + // If both integers have the same sign, // the sum of their absolute values can be returned. if lhs.is_negative == rhs.is_negative { let sum = lhs.abs + rhs.abs; I257Impl::new(sum, lhs.is_negative) } else { - // If the integers have different signs, + // If the integers have different signs, // the larger absolute value is subtracted from the smaller one. let (larger, smaller) = if lhs.abs >= rhs.abs { (lhs, rhs) @@ -61,10 +63,10 @@ impl i257Add of Add { } // Implements the AddEq trait for i257. -impl i257AddEq of AddEq { +impl i257AddEq of AddAssign { #[inline(always)] - fn add_eq(ref self: i257, other: i257) { - self = Add::add(self, other); + fn add_assign(ref self: i257, rhs: i257) { + self = Add::add(self, rhs); } } @@ -78,17 +80,18 @@ impl i257Sub of Sub { return lhs; } - // The subtraction of `lhs` to `rhs` is achieved by negating `rhs` sign and adding it to `lhs`. + // The subtraction of `lhs` to `rhs` is achieved by negating `rhs` sign and adding it to + // `lhs`. let neg_b = I257Impl::new(rhs.abs, !rhs.is_negative); lhs + neg_b } } // Implements the SubEq trait for i257. -impl i257SubEq of SubEq { +impl i257SubEq of SubAssign { #[inline(always)] - fn sub_eq(ref self: i257, other: i257) { - self = Sub::sub(self, other); + fn sub_assign(ref self: i257, rhs: i257) { + self = Sub::sub(self, rhs); } } @@ -107,10 +110,10 @@ impl i257Mul of Mul { } // Implements the MulEq trait for i257. -impl i257MulEq of MulEq { +impl i257MulEq of MulAssign { #[inline(always)] - fn mul_eq(ref self: i257, other: i257) { - self = Mul::mul(self, other); + fn mul_assign(ref self: i257, rhs: i257) { + self = Mul::mul(self, rhs); } } @@ -139,7 +142,8 @@ fn i257_div(lhs: i257, rhs: i257) -> i257 { return I257Impl::new(lhs.abs / rhs.abs, is_negative); } - // If the quotient is not an integer, multiply the dividend by 10 to move the decimal point over. + // If the quotient is not an integer, multiply the dividend by 10 to move the decimal point + // over. let quotient = (lhs.abs * 10) / rhs.abs; let last_digit = quotient % 10; @@ -159,10 +163,10 @@ impl i257Div of Div { } // Implements the DivEq trait for i257. -impl i257DivEq of DivEq { +impl i257DivEq of DivAssign { #[inline(always)] - fn div_eq(ref self: i257, other: i257) { - self = Div::div(self, other); + fn div_assign(ref self: i257, rhs: i257) { + self = Div::div(self, rhs); } } @@ -187,10 +191,10 @@ impl i257Rem of Rem { } // Implements the RemEq trait for i257. -impl i257RemEq of RemEq { +impl i257RemEq of RemAssign { #[inline(always)] - fn rem_eq(ref self: i257, other: i257) { - self = Rem::rem(self, other); + fn rem_assign(ref self: i257, rhs: i257) { + self = Rem::rem(self, rhs); } } @@ -217,7 +221,7 @@ impl i257PartialEq of PartialEq { } fn ne(lhs: @i257, rhs: @i257) -> bool { - !i257PartialEq::eq(lhs, rhs) + !Self::eq(lhs, rhs) } } @@ -226,14 +230,14 @@ impl i257PartialEq of PartialEq { // Ensure that neither `lhs` nor `rhs` is negative zero before calling. impl i257PartialOrd of PartialOrd { fn le(lhs: i257, rhs: i257) -> bool { - !i257PartialOrd::gt(lhs, rhs) + !Self::gt(lhs, rhs) } fn ge(lhs: i257, rhs: i257) -> bool { - i257PartialOrd::gt(lhs, rhs) || lhs == rhs + Self::gt(lhs, rhs) || lhs == rhs } fn lt(lhs: i257, rhs: i257) -> bool { - !i257PartialOrd::gt(lhs, rhs) && lhs != rhs + !Self::gt(lhs, rhs) && lhs != rhs } fn gt(lhs: i257, rhs: i257) -> bool { diff --git a/packages/math/src/is_prime.cairo b/packages/math/src/is_prime.cairo index 29f975c3..81def52e 100644 --- a/packages/math/src/is_prime.cairo +++ b/packages/math/src/is_prime.cairo @@ -3,7 +3,8 @@ use alexandria_math::fast_root::fast_sqrt; /// Check if the given number is prime /// # Arguments /// * `n` - The given number -/// * `iter` - The number of iterations to run when sqrting the number, the higher the more accurate (usually 10 is enough) +/// * `iter` - The number of iterations to run when sqrting the number, the higher the more accurate +/// (usually 10 is enough) /// # Returns /// * `bool` - if the given number is prime pub fn is_prime(n: u128, iter: usize) -> bool { diff --git a/packages/math/src/keccak256.cairo b/packages/math/src/keccak256.cairo index 0ce54e66..e73bd604 100644 --- a/packages/math/src/keccak256.cairo +++ b/packages/math/src/keccak256.cairo @@ -44,17 +44,21 @@ fn reverse_endianness(value: u256) -> u256 { /// # Returns /// /// A `u256` value representing the Keccak hash of the input bytes array. +#[deprecated( + feature: "deprecated-keccak", + note: "Use `core::keccak::compute_keccak_byte_array`.", + since: "2.7.0" +)] pub fn keccak256(mut self: Span) -> u256 { // Converts byte array to little endian 8 byte words array. let mut words64: Array = Default::default(); - while self - .len() >= 8 { - let current_word = self.slice(0, 8); - let (value, _) = U64Trait::from_le_bytes(current_word); - words64.append(value); - self = self.slice(8, self.len() - 8); - }; - // handle last word specifically + while self.len() >= 8 { + let current_word = self.slice(0, 8); + let (value, _) = U64Trait::from_le_bytes(current_word); + words64.append(value); + self = self.slice(8, self.len() - 8); + }; + // handle last word specifically let (last_word, last_word_bytes) = U64Trait::from_le_bytes(self); reverse_endianness(cairo_keccak(ref words64, last_word, last_word_bytes)) } diff --git a/packages/math/src/lcm_of_n_numbers.cairo b/packages/math/src/lcm_of_n_numbers.cairo index e7c69b2c..56316b72 100644 --- a/packages/math/src/lcm_of_n_numbers.cairo +++ b/packages/math/src/lcm_of_n_numbers.cairo @@ -19,10 +19,9 @@ pub fn lcm, +Into, +Mul, +Div, +Copy, +Drop< return Result::Err(LCMError::EmptyInput); } let mut a = *n.pop_front().unwrap(); - while let Option::Some(b) = n - .pop_front() { - let gcd: T = gcd_two_numbers(a.into(), (*b).into()).into(); - a = (a * *b) / gcd; - }; + for b in n { + let gcd: T = gcd_two_numbers(a.into(), (*b).into()).into(); + a = (a * *b) / gcd; + }; Result::Ok(a) } diff --git a/packages/math/src/lib.cairo b/packages/math/src/lib.cairo index 0e0e0afc..fa9f5696 100644 --- a/packages/math/src/lib.cairo +++ b/packages/math/src/lib.cairo @@ -25,14 +25,8 @@ pub mod trigonometry; pub mod u512_arithmetics; pub mod wad_ray_math; pub mod zellers_congruence; - - -use core::integer::{ - u8_wide_mul, u16_wide_mul, u32_wide_mul, u64_wide_mul, u128_wide_mul, u256_overflow_mul, - u8_wrapping_add, u16_wrapping_add, u32_wrapping_add, u64_wrapping_add, u128_wrapping_add, - u256_overflowing_add, u8_wrapping_sub, u16_wrapping_sub, u32_wrapping_sub, u64_wrapping_sub, - u128_wrapping_sub, u256_overflow_sub, BoundedInt -}; +use core::num::traits::Bounded; +use core::num::traits::{WrappingAdd, WrappingSub, WrappingMul, WideMul, OverflowingMul}; /// Raise a number to a power. /// O(log n) time complexity. @@ -69,71 +63,51 @@ fn count_digits_of_base(mut num: u128, base: u128) -> u128 { res } -pub trait BitShift { +pub trait BitShift< + T, +Sub, +Mul, +Div, +Rem, +PartialEq, +Into, +Drop, +Copy, +> { + // Cannot make SHL generic as u256 doesn't support everything required fn shl(x: T, n: T) -> T; - fn shr(x: T, n: T) -> T; + fn shr(x: T, n: T) -> T { + x / pow(2_u8.into(), n) + } } pub impl U8BitShift of BitShift { fn shl(x: u8, n: u8) -> u8 { - (u8_wide_mul(x, pow(2, n)) & BoundedInt::::max().into()).try_into().unwrap() - } - - fn shr(x: u8, n: u8) -> u8 { - x / pow(2, n) + (WideMul::wide_mul(x, pow(2, n)) & Bounded::::MAX.into()).try_into().unwrap() } } pub impl U16BitShift of BitShift { fn shl(x: u16, n: u16) -> u16 { - (u16_wide_mul(x, pow(2, n)) & BoundedInt::::max().into()).try_into().unwrap() - } - - fn shr(x: u16, n: u16) -> u16 { - x / pow(2, n) + (WideMul::wide_mul(x, pow(2, n)) & Bounded::::MAX.into()).try_into().unwrap() } } pub impl U32BitShift of BitShift { fn shl(x: u32, n: u32) -> u32 { - (u32_wide_mul(x, pow(2, n)) & BoundedInt::::max().into()).try_into().unwrap() - } - - fn shr(x: u32, n: u32) -> u32 { - x / pow(2, n) + (WideMul::wide_mul(x, pow(2, n)) & Bounded::::MAX.into()).try_into().unwrap() } } pub impl U64BitShift of BitShift { fn shl(x: u64, n: u64) -> u64 { - (u64_wide_mul(x, pow(2, n)) & BoundedInt::::max().into()).try_into().unwrap() - } - - fn shr(x: u64, n: u64) -> u64 { - x / pow(2, n) + (WideMul::wide_mul(x, pow(2, n)) & Bounded::::MAX.into()).try_into().unwrap() } } pub impl U128BitShift of BitShift { fn shl(x: u128, n: u128) -> u128 { - let (_, bottom_word) = u128_wide_mul(x, pow(2, n)); - bottom_word - } - - fn shr(x: u128, n: u128) -> u128 { - x / pow(2, n) + WideMul::wide_mul(x, pow(2, n)).low } } pub impl U256BitShift of BitShift { fn shl(x: u256, n: u256) -> u256 { - let (r, _) = u256_overflow_mul(x, pow(2, n)); + let (r, _) = x.overflowing_mul(pow(2, n)); r } - - fn shr(x: u256, n: u256) -> u256 { - x / pow(2, n) - } } /// Rotate the bits of an unsigned integer of type T @@ -156,7 +130,7 @@ trait BitRotate { pub impl U8BitRotate of BitRotate { fn rotate_left(x: u8, n: u8) -> u8 { - let word = u8_wide_mul(x, pow(2, n)); + let word = WideMul::wide_mul(x, pow(2, n)); let (quotient, remainder) = DivRem::div_rem(word, 0x100_u16.try_into().unwrap()); (quotient + remainder).try_into().unwrap() } @@ -170,7 +144,7 @@ pub impl U8BitRotate of BitRotate { pub impl U16BitRotate of BitRotate { fn rotate_left(x: u16, n: u16) -> u16 { - let word = u16_wide_mul(x, pow(2, n)); + let word = WideMul::wide_mul(x, pow(2, n)); let (quotient, remainder) = DivRem::div_rem(word, 0x10000_u32.try_into().unwrap()); (quotient + remainder).try_into().unwrap() } @@ -184,7 +158,7 @@ pub impl U16BitRotate of BitRotate { pub impl U32BitRotate of BitRotate { fn rotate_left(x: u32, n: u32) -> u32 { - let word = u32_wide_mul(x, pow(2, n)); + let word = WideMul::wide_mul(x, pow(2, n)); let (quotient, remainder) = DivRem::div_rem(word, 0x100000000_u64.try_into().unwrap()); (quotient + remainder).try_into().unwrap() } @@ -198,7 +172,7 @@ pub impl U32BitRotate of BitRotate { pub impl U64BitRotate of BitRotate { fn rotate_left(x: u64, n: u64) -> u64 { - let word = u64_wide_mul(x, pow(2, n)); + let word = WideMul::wide_mul(x, pow(2, n)); let (quotient, remainder) = DivRem::div_rem( word, 0x10000000000000000_u128.try_into().unwrap() ); @@ -214,8 +188,7 @@ pub impl U64BitRotate of BitRotate { pub impl U128BitRotate of BitRotate { fn rotate_left(x: u128, n: u128) -> u128 { - let (high, low) = u128_wide_mul(x, pow(2, n)); - let word = u256 { low, high }; + let word = WideMul::wide_mul(x, pow(2, n)); let (quotient, remainder) = DivRem::div_rem( word, u256 { low: 0, high: 1 }.try_into().unwrap() ); @@ -251,158 +224,16 @@ trait WrappingMath { pub impl WrappingMathImpl, +WrappingSub, +WrappingMul> of WrappingMath { #[inline(always)] fn wrapping_add(self: T, rhs: T) -> T { - WrappingAdd::::wrapping_add(self, rhs) + WrappingAdd::wrapping_add(self, rhs) } #[inline(always)] fn wrapping_sub(self: T, rhs: T) -> T { - WrappingSub::::wrapping_sub(self, rhs) + WrappingSub::wrapping_sub(self, rhs) } #[inline(always)] fn wrapping_mul(self: T, rhs: T) -> T { - WrappingMul::::wrapping_mul(self, rhs) - } -} - -trait WrappingAdd { - fn wrapping_add(self: T, rhs: T) -> T; -} - -trait WrappingSub { - fn wrapping_sub(self: T, rhs: T) -> T; -} - -trait WrappingMul { - fn wrapping_mul(self: T, rhs: T) -> T; -} - -pub impl U8WrappingAdd of WrappingAdd { - #[inline(always)] - fn wrapping_add(self: u8, rhs: u8) -> u8 { - u8_wrapping_add(self, rhs) - } -} - -pub impl U8WrappingSub of WrappingSub { - #[inline(always)] - fn wrapping_sub(self: u8, rhs: u8) -> u8 { - u8_wrapping_sub(self, rhs) - } -} - -pub impl U8WrappingMul of WrappingMul { - #[inline(always)] - fn wrapping_mul(self: u8, rhs: u8) -> u8 { - (u8_wide_mul(self, rhs) & BoundedInt::::max().into()).try_into().unwrap() - } -} - -pub impl U16WrappingAdd of WrappingAdd { - #[inline(always)] - fn wrapping_add(self: u16, rhs: u16) -> u16 { - u16_wrapping_add(self, rhs) - } -} - -pub impl U16WrappingSub of WrappingSub { - #[inline(always)] - fn wrapping_sub(self: u16, rhs: u16) -> u16 { - u16_wrapping_sub(self, rhs) - } -} - -pub impl U16WrappingMul of WrappingMul { - #[inline(always)] - fn wrapping_mul(self: u16, rhs: u16) -> u16 { - (u16_wide_mul(self, rhs) & BoundedInt::::max().into()).try_into().unwrap() - } -} - -pub impl U32WrappingAdd of WrappingAdd { - #[inline(always)] - fn wrapping_add(self: u32, rhs: u32) -> u32 { - u32_wrapping_add(self, rhs) - } -} - -pub impl U32WrappingSub of WrappingSub { - #[inline(always)] - fn wrapping_sub(self: u32, rhs: u32) -> u32 { - u32_wrapping_sub(self, rhs) - } -} - -pub impl U32WrappingMul of WrappingMul { - #[inline(always)] - fn wrapping_mul(self: u32, rhs: u32) -> u32 { - (u32_wide_mul(self, rhs) & BoundedInt::::max().into()).try_into().unwrap() - } -} - -pub impl U64WrappingAdd of WrappingAdd { - #[inline(always)] - fn wrapping_add(self: u64, rhs: u64) -> u64 { - u64_wrapping_add(self, rhs) - } -} - -pub impl U64WrappingSub of WrappingSub { - #[inline(always)] - fn wrapping_sub(self: u64, rhs: u64) -> u64 { - u64_wrapping_sub(self, rhs) - } -} - -pub impl U64WrappingMul of WrappingMul { - #[inline(always)] - fn wrapping_mul(self: u64, rhs: u64) -> u64 { - (u64_wide_mul(self, rhs) & BoundedInt::::max().into()).try_into().unwrap() - } -} - -pub impl U128WrappingAdd of WrappingAdd { - #[inline(always)] - fn wrapping_add(self: u128, rhs: u128) -> u128 { - u128_wrapping_add(self, rhs) - } -} - -pub impl U128WrappingSub of WrappingSub { - #[inline(always)] - fn wrapping_sub(self: u128, rhs: u128) -> u128 { - u128_wrapping_sub(self, rhs) - } -} - -pub impl U128WrappingMul of WrappingMul { - #[inline(always)] - fn wrapping_mul(self: u128, rhs: u128) -> u128 { - let (_, low) = u128_wide_mul(self, rhs); - low - } -} - -pub impl U256WrappingAdd of WrappingAdd { - #[inline(always)] - fn wrapping_add(self: u256, rhs: u256) -> u256 { - let (val, _) = u256_overflowing_add(self, rhs); - val - } -} - -pub impl U256WrappingSub of WrappingSub { - #[inline(always)] - fn wrapping_sub(self: u256, rhs: u256) -> u256 { - let (val, _) = u256_overflow_sub(self, rhs); - val - } -} - -pub impl U256WrappingMul of WrappingMul { - #[inline(always)] - fn wrapping_mul(self: u256, rhs: u256) -> u256 { - let (val, _) = u256_overflow_mul(self, rhs); - val + WrappingMul::wrapping_mul(self, rhs) } } diff --git a/packages/math/src/mod_arithmetics.cairo b/packages/math/src/mod_arithmetics.cairo index 9b7ec186..ff31a3bc 100644 --- a/packages/math/src/mod_arithmetics.cairo +++ b/packages/math/src/mod_arithmetics.cairo @@ -1,7 +1,5 @@ -use core::integer::{ - u512, u512_safe_div_rem_by_u256, u256_wide_mul, u128_wide_mul, u128_overflowing_add, - u128_wrapping_add -}; +use core::integer::{u512, u512_safe_div_rem_by_u256}; +use core::num::traits::{WrappingAdd, OverflowingAdd, OverflowingSub, WideMul}; use core::option::OptionTrait; use core::traits::TryInto; @@ -17,9 +15,10 @@ pub fn add_mod(a: u256, b: u256, modulo: u256) -> u256 { (a + b) % modulo } -/// Function that return the modular multiplicative inverse. Disclaimer: this function should only be used with a prime modulo. +/// Function that return the modular multiplicative inverse. Disclaimer: this function should only +/// be used with a prime modulo. /// # Arguments -/// * `b` - Number of which to find the multiplicative inverse of. +/// * `b` - Number of which to find the multiplicative inverse of. /// * `modulo` - modulo. /// # Returns /// * `u256` - modular multiplicative inverse @@ -51,10 +50,10 @@ pub fn sub_mod(mut a: u256, mut b: u256, modulo: u256) -> u256 { // reduce values a = a % modulo; b = b % modulo; - let (diff, overflow) = core::integer::u256_overflow_sub(a, b); + let (diff, overflow) = a.overflowing_sub(b); if overflow { // Overflow back with add modulo - let (diff, _) = core::integer::u256_overflowing_add(diff, modulo); + let (diff, _) = diff.overflowing_add(modulo); diff } else { diff @@ -70,37 +69,39 @@ pub fn sub_mod(mut a: u256, mut b: u256, modulo: u256) -> u256 { /// * `u256` - result of modular multiplication #[inline(always)] pub fn mult_mod(a: u256, b: u256, mod_non_zero: NonZero) -> u256 { - let mult: u512 = u256_wide_mul(a, b); + let mult: u512 = WideMul::wide_mul(a, b); let (_, rem_u256) = u512_safe_div_rem_by_u256(mult, mod_non_zero); rem_u256 } #[inline(always)] // core::integer::u128_add_with_carry -fn u128_add_with_carry(a: u128, b: u128) -> (u128, u128) nopanic { - match u128_overflowing_add(a, b) { - Result::Ok(v) => (v, 0), - Result::Err(v) => (v, 1), +fn u128_add_with_carry(a: u128, b: u128) -> (u128, u128) { + let (v, did_overflow) = a.overflowing_add(b); + if did_overflow { + (v, 1) + } else { + (v, 0) } } -pub fn u256_wide_sqr(a: u256) -> u512 nopanic { - let (limb1, limb0) = u128_wide_mul(a.low, a.low); - let (limb2, limb1_part) = u128_wide_mul(a.low, a.high); +pub fn u256_wide_sqr(a: u256) -> u512 { + let u256 { high: limb1, low: limb0, } = WideMul::wide_mul(a.low, a.low); + let u256 { high: limb2, low: limb1_part } = WideMul::wide_mul(a.low, a.high); let (limb1, limb1_overflow0) = u128_add_with_carry(limb1, limb1_part); let (limb1, limb1_overflow1) = u128_add_with_carry(limb1, limb1_part); let (limb2, limb2_overflow) = u128_add_with_carry(limb2, limb2); - let (limb3, limb2_part) = u128_wide_mul(a.high, a.high); + let u256 { high: limb3, low: limb2_part } = WideMul::wide_mul(a.high, a.high); // No overflow since no limb4. - let limb3 = u128_wrapping_add(limb3, limb2_overflow); + let limb3 = limb3.wrapping_add(limb2_overflow); let (limb2, limb2_overflow) = u128_add_with_carry(limb2, limb2_part); // No overflow since no limb4. - let limb3 = u128_wrapping_add(limb3, limb2_overflow); + let limb3 = limb3.wrapping_add(limb2_overflow); // No overflow possible in this addition since both operands are 0/1. - let limb1_overflow = u128_wrapping_add(limb1_overflow0, limb1_overflow1); + let limb1_overflow = limb1_overflow0.wrapping_add(limb1_overflow1); let (limb2, limb2_overflow) = u128_add_with_carry(limb2, limb1_overflow); // No overflow since no limb4. - let limb3 = u128_wrapping_add(limb3, limb2_overflow); + let limb3 = limb3.wrapping_add(limb2_overflow); u512 { limb0, limb1, limb2, limb3 } } diff --git a/packages/math/src/sha256.cairo b/packages/math/src/sha256.cairo index 90eed9d3..6e7264e1 100644 --- a/packages/math/src/sha256.cairo +++ b/packages/math/src/sha256.cairo @@ -1,7 +1,8 @@ -use core::integer::{u32_wrapping_add, BoundedInt}; +use core::num::traits::Bounded; +use core::num::traits::OverflowingAdd; fn ch(x: u32, y: u32, z: u32) -> u32 { - (x & y) ^ ((x ^ BoundedInt::::max().into()) & z) + (x & y) ^ ((x ^ Bounded::::MAX.into()) & z) } fn maj(x: u32, y: u32, z: u32) -> u32 { @@ -13,7 +14,7 @@ fn bsig0(x: u32) -> u32 { let x1 = (x / 0x4) | (x * 0x40000000); let x2 = (x / 0x2000) | (x * 0x80000); let x3 = (x / 0x400000) | (x * 0x400); - let result = (x1 ^ x2 ^ x3) & BoundedInt::::max().into(); + let result = (x1 ^ x2 ^ x3) & Bounded::::MAX.into(); result.try_into().unwrap() } @@ -22,7 +23,7 @@ fn bsig1(x: u32) -> u32 { let x1 = (x / 0x40) | (x * 0x4000000); let x2 = (x / 0x800) | (x * 0x200000); let x3 = (x / 0x2000000) | (x * 0x80); - let result = (x1 ^ x2 ^ x3) & BoundedInt::::max().into(); + let result = (x1 ^ x2 ^ x3) & Bounded::::MAX.into(); result.try_into().unwrap() } @@ -31,7 +32,7 @@ fn ssig0(x: u32) -> u32 { let x1 = (x / 0x80) | (x * 0x2000000); let x2 = (x / 0x40000) | (x * 0x4000); let x3 = (x / 0x8); - let result = (x1 ^ x2 ^ x3) & BoundedInt::::max().into(); + let result = (x1 ^ x2 ^ x3) & Bounded::::MAX.into(); result.try_into().unwrap() } @@ -40,10 +41,15 @@ fn ssig1(x: u32) -> u32 { let x1 = (x / 0x20000) | (x * 0x8000); let x2 = (x / 0x80000) | (x * 0x2000); let x3 = (x / 0x400); - let result = (x1 ^ x2 ^ x3) & BoundedInt::::max().into(); + let result = (x1 ^ x2 ^ x3) & Bounded::::MAX.into(); result.try_into().unwrap() } +#[deprecated( + feature: "deprecated-sha256", + note: "Use `core::sha256::compute_sha256_byte_array`.", + since: "2.7.0" +)] pub fn sha256(mut data: Array) -> Array { let data_len: u64 = (data.len() * 8).into(); @@ -73,8 +79,6 @@ pub fn sha256(mut data: Array) -> Array { data.append(res.try_into().unwrap()); let data = from_u8Array_to_u32Array(data.span()); - let h = get_h(); - let k = get_k(); let res = sha256_inner(data.span(), 0, k.span(), h.span()); from_u32Array_to_u8Array(res) @@ -82,17 +86,16 @@ pub fn sha256(mut data: Array) -> Array { fn from_u32Array_to_u8Array(mut data: Span) -> Array { let mut result = array![]; - while let Option::Some(val) = data - .pop_front() { - let mut res = (*val & 0xff000000) / 0x1000000; - result.append(res.try_into().unwrap()); - res = (*val & 0xff0000) / 0x10000; - result.append(res.try_into().unwrap()); - res = (*val & 0xff00) / 0x100; - result.append(res.try_into().unwrap()); - res = *val & 0xff; - result.append(res.try_into().unwrap()); - }; + for val in data { + let mut res = (*val & 0xff000000) / 0x1000000; + result.append(res.try_into().unwrap()); + res = (*val & 0xff0000) / 0x10000; + result.append(res.try_into().unwrap()); + res = (*val & 0xff00) / 0x100; + result.append(res.try_into().unwrap()); + res = *val & 0xff; + result.append(res.try_into().unwrap()); + }; result } @@ -104,14 +107,22 @@ fn sha256_inner(mut data: Span, i: usize, k: Span, mut h: Span) - let h2 = compression(w, 0, k, h); let mut t = array![]; - t.append(u32_wrapping_add(*h[0], *h2[0])); - t.append(u32_wrapping_add(*h[1], *h2[1])); - t.append(u32_wrapping_add(*h[2], *h2[2])); - t.append(u32_wrapping_add(*h[3], *h2[3])); - t.append(u32_wrapping_add(*h[4], *h2[4])); - t.append(u32_wrapping_add(*h[5], *h2[5])); - t.append(u32_wrapping_add(*h[6], *h2[6])); - t.append(u32_wrapping_add(*h[7], *h2[7])); + let (tmp, _) = (*h[0]).overflowing_add(*h2[0]); + t.append(tmp); + let (tmp, _) = (*h[1]).overflowing_add(*h2[1]); + t.append(tmp); + let (tmp, _) = (*h[2]).overflowing_add(*h2[2]); + t.append(tmp); + let (tmp, _) = (*h[3]).overflowing_add(*h2[3]); + t.append(tmp); + let (tmp, _) = (*h[4]).overflowing_add(*h2[4]); + t.append(tmp); + let (tmp, _) = (*h[5]).overflowing_add(*h2[5]); + t.append(tmp); + let (tmp, _) = (*h[6]).overflowing_add(*h2[6]); + t.append(tmp); + let (tmp, _) = (*h[7]).overflowing_add(*h2[7]); + t.append(tmp); h = t.span(); sha256_inner(data, i + 1, k, h) } @@ -122,18 +133,21 @@ fn compression(w: Span, i: usize, k: Span, mut h: Span) -> Span, i: usize) -> Span { while (i < 64) { let s0 = ssig0(*result[i - 15]); let s1 = ssig1(*result[i - 2]); - let res = u32_wrapping_add( - u32_wrapping_add(u32_wrapping_add(*result[i - 16], s0), *result[i - 7]), s1 - ); + + let (tmp, _) = (*result[i - 16]).overflowing_add(s0); + let (tmp, _) = tmp.overflowing_add(*result[i - 7]); + let (res, _) = tmp.overflowing_add(s1); result.append(res); i += 1; }; @@ -163,98 +178,90 @@ fn create_message_schedule(data: Span, i: usize) -> Span { fn from_u8Array_to_u32Array(mut data: Span) -> Array { let mut result = array![]; - while let Option::Some(val1) = data - .pop_front() { - let val2 = data.pop_front().unwrap(); - let val3 = data.pop_front().unwrap(); - let val4 = data.pop_front().unwrap(); - let mut value = (*val1).into() * 0x1000000; - value = value + (*val2).into() * 0x10000; - value = value + (*val3).into() * 0x100; - value = value + (*val4).into(); - result.append(value); - }; + while let Option::Some(val1) = data.pop_front() { + let val2 = data.pop_front().unwrap(); + let val3 = data.pop_front().unwrap(); + let val4 = data.pop_front().unwrap(); + let mut value = (*val1).into() * 0x1000000; + value = value + (*val2).into() * 0x10000; + value = value + (*val3).into() * 0x100; + value = value + (*val4).into(); + result.append(value); + }; result } -fn get_h() -> Array { - array![ - 0x6a09e667, - 0xbb67ae85, - 0x3c6ef372, - 0xa54ff53a, - 0x510e527f, - 0x9b05688c, - 0x1f83d9ab, - 0x5be0cd19 - ] -} +const h: [ + u32 + ; 8] = [ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 +]; -fn get_k() -> Array { - array![ - 0x428a2f98, - 0x71374491, - 0xb5c0fbcf, - 0xe9b5dba5, - 0x3956c25b, - 0x59f111f1, - 0x923f82a4, - 0xab1c5ed5, - 0xd807aa98, - 0x12835b01, - 0x243185be, - 0x550c7dc3, - 0x72be5d74, - 0x80deb1fe, - 0x9bdc06a7, - 0xc19bf174, - 0xe49b69c1, - 0xefbe4786, - 0x0fc19dc6, - 0x240ca1cc, - 0x2de92c6f, - 0x4a7484aa, - 0x5cb0a9dc, - 0x76f988da, - 0x983e5152, - 0xa831c66d, - 0xb00327c8, - 0xbf597fc7, - 0xc6e00bf3, - 0xd5a79147, - 0x06ca6351, - 0x14292967, - 0x27b70a85, - 0x2e1b2138, - 0x4d2c6dfc, - 0x53380d13, - 0x650a7354, - 0x766a0abb, - 0x81c2c92e, - 0x92722c85, - 0xa2bfe8a1, - 0xa81a664b, - 0xc24b8b70, - 0xc76c51a3, - 0xd192e819, - 0xd6990624, - 0xf40e3585, - 0x106aa070, - 0x19a4c116, - 0x1e376c08, - 0x2748774c, - 0x34b0bcb5, - 0x391c0cb3, - 0x4ed8aa4a, - 0x5b9cca4f, - 0x682e6ff3, - 0x748f82ee, - 0x78a5636f, - 0x84c87814, - 0x8cc70208, - 0x90befffa, - 0xa4506ceb, - 0xbef9a3f7, - 0xc67178f2 - ] -} +const k: [ + u32 + ; 64] = [ + 0x428a2f98, + 0x71374491, + 0xb5c0fbcf, + 0xe9b5dba5, + 0x3956c25b, + 0x59f111f1, + 0x923f82a4, + 0xab1c5ed5, + 0xd807aa98, + 0x12835b01, + 0x243185be, + 0x550c7dc3, + 0x72be5d74, + 0x80deb1fe, + 0x9bdc06a7, + 0xc19bf174, + 0xe49b69c1, + 0xefbe4786, + 0x0fc19dc6, + 0x240ca1cc, + 0x2de92c6f, + 0x4a7484aa, + 0x5cb0a9dc, + 0x76f988da, + 0x983e5152, + 0xa831c66d, + 0xb00327c8, + 0xbf597fc7, + 0xc6e00bf3, + 0xd5a79147, + 0x06ca6351, + 0x14292967, + 0x27b70a85, + 0x2e1b2138, + 0x4d2c6dfc, + 0x53380d13, + 0x650a7354, + 0x766a0abb, + 0x81c2c92e, + 0x92722c85, + 0xa2bfe8a1, + 0xa81a664b, + 0xc24b8b70, + 0xc76c51a3, + 0xd192e819, + 0xd6990624, + 0xf40e3585, + 0x106aa070, + 0x19a4c116, + 0x1e376c08, + 0x2748774c, + 0x34b0bcb5, + 0x391c0cb3, + 0x4ed8aa4a, + 0x5b9cca4f, + 0x682e6ff3, + 0x748f82ee, + 0x78a5636f, + 0x84c87814, + 0x8cc70208, + 0x90befffa, + 0xa4506ceb, + 0xbef9a3f7, + 0xc67178f2 +]; diff --git a/packages/math/src/sha512.cairo b/packages/math/src/sha512.cairo index 92fe0cc7..8d457bf5 100644 --- a/packages/math/src/sha512.cairo +++ b/packages/math/src/sha512.cairo @@ -1,4 +1,5 @@ -use core::integer::{u64_wrapping_add, BoundedInt}; +use core::num::traits::Bounded; +use core::num::traits::WrappingAdd; use core::traits::{BitAnd, BitXor, BitOr}; use super::BitShift; @@ -75,13 +76,13 @@ impl WordBitOr of BitOr { impl WordBitNot of BitNot { fn bitnot(a: Word64) -> Word64 { - Word64 { data: BoundedInt::max() - a.data } + Word64 { data: Bounded::MAX - a.data } } } impl WordAdd of Add { fn add(lhs: Word64, rhs: Word64) -> Word64 { - Word64 { data: u64_wrapping_add(lhs.data, rhs.data) } + Word64 { data: lhs.data.wrapping_add(rhs.data) } } } @@ -204,13 +205,18 @@ pub fn fpow(mut base: u128, mut power: u128) -> u128 { result } +const two_squarings: [ + u64 + ; 6] = [ + TWO_POW_1, TWO_POW_2, TWO_POW_4, TWO_POW_8, TWO_POW_16, TWO_POW_32 +]; // Uses cache for faster powers of 2 in a u128 // Uses TWO_POW_* constants // Generic T to use with both u128 and u64 pub fn two_pow, +Mul, +Into, +Drop>(mut power: u64) -> T { - let two_squarings = array![TWO_POW_1, TWO_POW_2, TWO_POW_4, TWO_POW_8, TWO_POW_16, TWO_POW_32,]; let mut i = 0; let mut result: T = 1_u64.into(); + let two_squarings = two_squarings.span(); while (power != 0) { let (q, r) = DivRem::div_rem(power, 2); if r == 1 { @@ -249,12 +255,12 @@ fn math_shr_precomputed, +Rem, +Drop, +Copy, +Into> // Shift left wrapper for u64 fn math_shl_u64(x: u64, n: u64) -> u64 { - (math_shl(x.into(), n) % BoundedInt::::max().into()).try_into().unwrap() + (math_shl(x.into(), n) % Bounded::::MAX.into()).try_into().unwrap() } // Shift right wrapper for u64 fn math_shr_u64(x: u64, n: u64) -> u64 { - (math_shr(x.into(), n) % BoundedInt::::max().into()).try_into().unwrap() + (math_shr(x.into(), n) % Bounded::::MAX.into()).try_into().unwrap() } fn add_trailing_zeroes(ref data: Array, msg_len: usize) { @@ -395,7 +401,7 @@ fn digest_hash(data: Span, msg_len: usize) -> Array { pub fn sha512(mut data: Array) -> Array { let bit_numbers: u128 = data.len().into() * 8; // any u32 * 8 fits in u64 - // let bit_numbers = bit_numbers & BoundedInt::::max().into(); + // let bit_numbers = bit_numbers & Bounded::::MAX.into(); let max_u8: u128 = MAX_U8.into(); let mut msg_len = data.len(); diff --git a/packages/math/src/tests/aliquot_sum_test.cairo b/packages/math/src/tests/aliquot_sum_test.cairo index ce80d3d0..608debf2 100644 --- a/packages/math/src/tests/aliquot_sum_test.cairo +++ b/packages/math/src/tests/aliquot_sum_test.cairo @@ -3,41 +3,41 @@ use alexandria_math::aliquot_sum::aliquot_sum; #[test] #[available_gas(200000)] fn zero_test() { - assert_eq!(aliquot_sum(0), 0, "invalid result"); + assert_eq!(aliquot_sum(0), 0); } #[test] #[available_gas(200000)] fn one_test() { - assert_eq!(aliquot_sum(1), 0, "invalid result"); + assert_eq!(aliquot_sum(1), 0); } #[test] #[available_gas(200000)] fn two_test() { - assert_eq!(aliquot_sum(2), 1, "invalid result"); + assert_eq!(aliquot_sum(2), 1); } #[test] #[available_gas(200000)] fn one_digit_number_test() { - assert_eq!(aliquot_sum(6), 6, "invalid result"); + assert_eq!(aliquot_sum(6), 6); } #[test] #[available_gas(2000000)] fn two_digit_number_test() { - assert_eq!(aliquot_sum(15), 9, "invalid result"); + assert_eq!(aliquot_sum(15), 9); } #[test] #[available_gas(20000000)] fn three_digit_number_test() { - assert_eq!(aliquot_sum(343), 57, "invalid result"); + assert_eq!(aliquot_sum(343), 57); } #[test] #[available_gas(2000000)] fn two_digit_prime_number_test() { - assert_eq!(aliquot_sum(17), 1, "invalid result"); + assert_eq!(aliquot_sum(17), 1); } diff --git a/packages/math/src/tests/collatz_sequence_test.cairo b/packages/math/src/tests/collatz_sequence_test.cairo index 6a8a28d7..6c39763a 100644 --- a/packages/math/src/tests/collatz_sequence_test.cairo +++ b/packages/math/src/tests/collatz_sequence_test.cairo @@ -3,17 +3,17 @@ use alexandria_math::collatz_sequence::sequence; #[test] #[available_gas(2000000)] fn collatz_sequence_10_test() { - assert_eq!(sequence(10).len(), 7, "invalid result"); + assert_eq!(sequence(10).len(), 7); } #[test] #[available_gas(2000000)] fn collatz_sequence_15_test() { - assert_eq!(sequence(15).len(), 18, "invalid result"); + assert_eq!(sequence(15).len(), 18); } #[test] #[available_gas(2000000)] fn collatz_sequence_empty_test() { - assert_eq!(sequence(0).len(), 0, "invalid result"); + assert_eq!(sequence(0).len(), 0); } diff --git a/packages/math/src/tests/ed25519_test.cairo b/packages/math/src/tests/ed25519_test.cairo index 0ebf8cb9..3cb0ff31 100644 --- a/packages/math/src/tests/ed25519_test.cairo +++ b/packages/math/src/tests/ed25519_test.cairo @@ -1,6 +1,7 @@ use alexandria_math::ed25519::{verify_signature, Point, PointOperations, p_non_zero}; -// Public keys and signatures were generated with JS library Noble (https://github.com/paulmillr/noble-ed25519) +// Public keys and signatures were generated with JS library Noble +// (https://github.com/paulmillr/noble-ed25519) #[test] #[available_gas(3200000000)] @@ -13,7 +14,7 @@ fn verify_signature_test_0() { let s_sign: u256 = 0x6a9473f6492676e988709498b228df873fe3cfdf59255b1a9e1add4f87ec610b; let signature = array![r_sign, s_sign]; - assert!(verify_signature(msg, signature.span(), pub_key), "Invalid signature"); + assert!(verify_signature(msg, signature.span(), pub_key)); } #[test] @@ -27,7 +28,7 @@ fn verify_signature_test_1() { let s_sign: u256 = 0x7d1308162466f8e6097f8afa310c074796d13459d4b53cdecf80ca7413410000; let signature = array![r_sign, s_sign]; - assert!(verify_signature(msg, signature.span(), pub_key), "Invalid signature"); + assert!(verify_signature(msg, signature.span(), pub_key)); } #[test] @@ -41,7 +42,7 @@ fn verify_signature_test_2() { let s_sign: u256 = 0xcc2e419abf32f91bc20419ba0905ad52923c7c110d14623b62300711b8f9370c; let signature = array![r_sign, s_sign]; - assert!(verify_signature(msg, signature.span(), pub_key), "Invalid signature"); + assert!(verify_signature(msg, signature.span(), pub_key)); } #[test] @@ -55,7 +56,7 @@ fn verify_signature_test_3() { let s_sign: u256 = 0x68e015fa8775659d1f40a01e1f69b8af4409046f4dc8ff02cdb04fdc3585eb0d; let signature = array![r_sign, s_sign]; - assert!(verify_signature(msg, signature.span(), pub_key), "Invalid signature"); + assert!(verify_signature(msg, signature.span(), pub_key)); } #[test] @@ -69,7 +70,7 @@ fn verify_signature_invalid() { let s_sign: u256 = 0x68e015fa8775659d1f40a01e1f69b8af4409046f4dc8ff02cdb04fdc3585eb01; let signature = array![r_sign, s_sign]; - assert!(!verify_signature(msg, signature.span(), pub_key), "Signature should be invalid"); + assert!(!verify_signature(msg, signature.span(), pub_key)); } #[test] @@ -83,8 +84,8 @@ fn verify_signature_invalid_length() { let s_sign: u256 = 0x68e015fa8775659d1f40a01e1f69b8af4409046f4dc8ff02cdb04fdc3585eb0d; let signature = array![r_sign, s_sign, s_sign]; - assert!(!verify_signature(msg, signature.span(), pub_key), "Invalid signature"); - assert!(!verify_signature(msg, array![r_sign].span(), pub_key), "Invalid signature"); + assert!(!verify_signature(msg, signature.span(), pub_key)); + assert!(!verify_signature(msg, array![r_sign].span(), pub_key)); } #[test] @@ -101,5 +102,5 @@ fn affine_point_op() { x: 34426924428514608760437100447421064591311588584549077394333265447466212246087, y: 29872771498517479181395568267318965384440757492476580330810382845026939417492 }; - assert(res == p1.add(p2, p_non_zero), 'incorrect point addition'); + assert!(res == p1.add(p2, p_non_zero)); } diff --git a/packages/math/src/tests/extended_euclidean_algorithm_test.cairo b/packages/math/src/tests/extended_euclidean_algorithm_test.cairo index 7bffcecb..af5b4ca6 100644 --- a/packages/math/src/tests/extended_euclidean_algorithm_test.cairo +++ b/packages/math/src/tests/extended_euclidean_algorithm_test.cairo @@ -1,25 +1,24 @@ -use alexandria_math::extended_euclidean_algorithm::{extended_euclidean_algorithm,}; -use core::integer::u128_wrapping_sub; +use alexandria_math::extended_euclidean_algorithm::{extended_euclidean_algorithm}; +use core::num::traits::WrappingSub; // Define a test case function to avoid code duplication. fn test_case(a: u128, b: u128, expected: (u128, u128, u128)) { let (gcd, x, y) = extended_euclidean_algorithm(a, b); let (expected_gcd, expected_x, expected_y) = expected; - assert_eq!(gcd, expected_gcd, "gcd is incorrect"); + assert_eq!(gcd, expected_gcd); - assert_eq!(x, expected_x, "x is incorrect"); - assert_eq!(y, expected_y, "y is incorrect"); + assert_eq!(x, expected_x); + assert_eq!(y, expected_y); } #[test] #[available_gas(2000000)] fn extended_euclidean_algorithm_test() { - // TODO This needs to be update - test_case(101, 13, (1, 4, u128_wrapping_sub(0, 31))); - test_case(123, 19, (1, u128_wrapping_sub(0, 2), 13)); - test_case(25, 36, (1, 13, u128_wrapping_sub(0, 9))); - test_case(69, 54, (3, u128_wrapping_sub(0, 7), 9)); - test_case(55, 79, (1, 23, u128_wrapping_sub(0, 16))); - test_case(33, 44, (11, u128_wrapping_sub(0, 1), 1)); - test_case(50, 70, (10, 3, u128_wrapping_sub(0, 2))); + test_case(101, 13, (1, 4, 0.wrapping_sub(31))); + test_case(123, 19, (1, 0.wrapping_sub(2), 13)); + test_case(25, 36, (1, 13, 0.wrapping_sub(9))); + test_case(69, 54, (3, 0.wrapping_sub(7), 9)); + test_case(55, 79, (1, 23, 0.wrapping_sub(16))); + test_case(33, 44, (11, 0.wrapping_sub(1), 1)); + test_case(50, 70, (10, 3, 0.wrapping_sub(2))); } diff --git a/packages/math/src/tests/fast_power_test.cairo b/packages/math/src/tests/fast_power_test.cairo index e2aabc2a..d6af0bfc 100644 --- a/packages/math/src/tests/fast_power_test.cairo +++ b/packages/math/src/tests/fast_power_test.cairo @@ -3,14 +3,14 @@ use alexandria_math::fast_power::{fast_power, fast_power_mod}; #[test] #[available_gas(1000000000)] fn fast_power_test() { - assert_eq!(fast_power(2_u128, 1_u128), 2, "invalid result"); - assert_eq!(fast_power(2_u128, 2_u128), 4, "invalid result"); - assert_eq!(fast_power(2_u128, 3_u128), 8, "invalid result"); - assert_eq!(fast_power(3_u128, 4_u128), 81, "invalid result"); - assert_eq!(fast_power(2_u128, 100_u128), 0x10000000000000000000000000, "invalid result"); - assert_eq!(fast_power(2_u128, 127_u128), 0x80000000000000000000000000000000, "invalid result"); + assert_eq!(fast_power(2_u128, 1_u128), 2); + assert_eq!(fast_power(2_u128, 2_u128), 4); + assert_eq!(fast_power(2_u128, 3_u128), 8); + assert_eq!(fast_power(3_u128, 4_u128), 81); + assert_eq!(fast_power(2_u128, 100_u128), 0x10000000000000000000000000); + assert_eq!(fast_power(2_u128, 127_u128), 0x80000000000000000000000000000000); - assert_eq!(fast_power(2_u256, 128_u256), 0x100000000000000000000000000000000, "invalid result"); + assert_eq!(fast_power(2_u256, 128_u256), 0x100000000000000000000000000000000); assert_eq!( fast_power(2_u256, 255_u256), @@ -22,29 +22,21 @@ fn fast_power_test() { #[test] #[available_gas(1000000000)] fn fast_power_mod_test() { - assert_eq!(fast_power_mod(2_u128, 1_u128, 17_u128), 2, "invalid result"); - assert_eq!(fast_power_mod(2_u128, 2_u128, 17_u128), 4, "invalid result"); - assert_eq!(fast_power_mod(2_u128, 3_u128, 17_u128), 8, "invalid result"); - assert_eq!(fast_power_mod(3_u128, 4_u128, 17_u128), 13, "invalid result"); - assert_eq!(fast_power_mod(2_u128, 100_u128, 1000000007_u128), 976371285, "invalid result"); - assert( - fast_power_mod( - 2_u128, 127_u128, 340282366920938463463374607431768211454_u128 - ) == 170141183460469231731687303715884105728, - 'invalid result' - ); + assert_eq!(fast_power_mod(2_u128, 1_u128, 17_u128), 2); + assert_eq!(fast_power_mod(2_u128, 2_u128, 17_u128), 4); + assert_eq!(fast_power_mod(2_u128, 3_u128, 17_u128), 8); + assert_eq!(fast_power_mod(3_u128, 4_u128, 17_u128), 13); + assert_eq!(fast_power_mod(2_u128, 100_u128, 1000000007_u128), 976371285); assert_eq!( - fast_power_mod(2_u128, 127_u128, 34028236692093846346337460743176821144_u128), - 8, - "invalid result" + fast_power_mod(2_u128, 127_u128, 340282366920938463463374607431768211454_u128), + 170141183460469231731687303715884105728 ); + assert_eq!(fast_power_mod(2_u128, 127_u128, 34028236692093846346337460743176821144_u128), 8); - assert_eq!(fast_power_mod(2_u128, 128_u128, 9299_u128), 1412, "invalid result"); + assert_eq!(fast_power_mod(2_u128, 128_u128, 9299_u128), 1412); - assert( - fast_power_mod( - 2_u128, 88329_u128, 34028236692093846346337460743176821144_u128 - ) == 2199023255552, - 'invalid result' + assert_eq!( + fast_power_mod(2_u128, 88329_u128, 34028236692093846346337460743176821144_u128), + 2199023255552 ); } diff --git a/packages/math/src/tests/fast_root_test.cairo b/packages/math/src/tests/fast_root_test.cairo index 565206f5..b12f8b93 100644 --- a/packages/math/src/tests/fast_root_test.cairo +++ b/packages/math/src/tests/fast_root_test.cairo @@ -5,29 +5,29 @@ use alexandria_math::fast_root::fast_sqrt; #[test] #[available_gas(5000000)] fn fast_sqrt_test_1() { - assert_eq!(fast_sqrt(100, 10), 10, "invalid result"); + assert_eq!(fast_sqrt(100, 10), 10); } #[test] #[available_gas(5000000)] fn fast_sqrt_test_2() { - assert_eq!(fast_sqrt(79, 10), 9, "invalid result"); + assert_eq!(fast_sqrt(79, 10), 9); } #[test] #[available_gas(5000000)] fn fast_curt_test_1() { - assert_eq!(fast_cbrt(1000, 10), 10, "invalid result"); + assert_eq!(fast_cbrt(1000, 10), 10); } #[test] #[available_gas(5000000)] fn fast_nr_optimize_test_1() { - assert_eq!(fast_nr_optimize(10000, 4, 30), 10, "invalid result"); + assert_eq!(fast_nr_optimize(10000, 4, 30), 10); } #[test] #[available_gas(5000000)] fn fast_nr_optimize_test_2() { - assert_eq!(fast_nr_optimize(10, 1, 10), 10, "invalid result"); + assert_eq!(fast_nr_optimize(10, 1, 10), 10); } diff --git a/packages/math/src/tests/fibonacci_test.cairo b/packages/math/src/tests/fibonacci_test.cairo index 03b3430a..3ec5c1cc 100644 --- a/packages/math/src/tests/fibonacci_test.cairo +++ b/packages/math/src/tests/fibonacci_test.cairo @@ -3,6 +3,6 @@ use alexandria_math::fibonacci::fib; #[test] #[available_gas(200000)] fn fibonacci_test() { - assert_eq!(fib(0, 1, 10), 55, "invalid result"); - assert_eq!(fib(2, 4, 8), 110, "invalid result"); + assert_eq!(fib(0, 1, 10), 55); + assert_eq!(fib(2, 4, 8), 110); } diff --git a/packages/math/src/tests/gcd_of_n_numbers_test.cairo b/packages/math/src/tests/gcd_of_n_numbers_test.cairo index 43293afd..25c6d8a7 100644 --- a/packages/math/src/tests/gcd_of_n_numbers_test.cairo +++ b/packages/math/src/tests/gcd_of_n_numbers_test.cairo @@ -4,21 +4,21 @@ use alexandria_math::gcd_of_n_numbers::gcd; #[available_gas(1000000000)] fn gcd_test() { let arr = array![2, 4, 6, 8, 10]; - assert_eq!(gcd(arr.span()), 2, "invalid result"); + assert_eq!(gcd(arr.span()), 2); } #[test] #[available_gas(1000000000)] fn gcd_test_inverse() { let arr = array![10, 8, 6, 4, 2]; - assert_eq!(gcd(arr.span()), 2, "invalid result"); + assert_eq!(gcd(arr.span()), 2); } #[test] #[available_gas(1000000000)] fn gcd_test_3() { let arr = array![3, 6, 12, 99]; - assert_eq!(gcd(arr.span()), 3, "invalid result"); + assert_eq!(gcd(arr.span()), 3); } @@ -26,7 +26,7 @@ fn gcd_test_3() { #[available_gas(1000000000)] fn gcd_single_test() { let arr = array![10]; - assert_eq!(gcd(arr.span()), 10, "invalid result"); + assert_eq!(gcd(arr.span()), 10); } #[test] diff --git a/packages/math/src/tests/i257_test.cairo b/packages/math/src/tests/i257_test.cairo index 2d5a732a..91a80804 100644 --- a/packages/math/src/tests/i257_test.cairo +++ b/packages/math/src/tests/i257_test.cairo @@ -7,35 +7,35 @@ fn i257_test_add() { let a = I257Impl::new(42, false); let b = I257Impl::new(13, false); let result = a + b; - assert_eq!(result.abs(), 55, "42 + 13 = 55"); + assert_eq!(result.abs(), 55); assert!(!result.is_negative(), "42 + 13 -> positive"); // Test addition of two negative integers let a = I257Impl::new(42, true); let b = I257Impl::new(13, true); let result = a + b; - assert_eq!(result.abs(), 55, "-42 - 13 = -55"); + assert_eq!(result.abs(), 55); assert!(result.is_negative(), "-42 - 13 -> negative"); // Test addition of a positive integer and a negative integer with the same magnitude let a = I257Impl::new(42, false); let b = I257Impl::new(42, true); let result = a + b; - assert_eq!(result.abs(), 0, "42 - 42 = 0"); + assert_eq!(result.abs(), 0); assert!(!result.is_negative(), "42 - 42 -> positive"); // Test addition of a positive integer and a negative integer with different magnitudes let a = I257Impl::new(42, false); let b = I257Impl::new(13, true); let result = a + b; - assert_eq!(result.abs(), 29, "42 - 13 = 29"); + assert_eq!(result.abs(), 29); assert!(!result.is_negative(), "42 - 13 -> positive"); // Test addition of a negative integer and a positive integer with different magnitudes let a = I257Impl::new(42, true); let b = I257Impl::new(13, false); let result = a + b; - assert_eq!(result.abs(), 29, "-42 + 13 = -29"); + assert_eq!(result.abs(), 29); assert!(result.is_negative(), "-42 + 13 -> negative"); } @@ -45,63 +45,63 @@ fn i257_test_sub() { let a = I257Impl::new(42, false); let b = I257Impl::new(13, false); let result = a - b; - assert_eq!(result.abs(), 29, "42 - 13 = 29"); + assert_eq!(result.abs(), 29); assert!(!result.is_negative(), "42 - 13 -> positive"); // Test subtraction of two positive integers with larger second let a = I257Impl::new(13, false); let b = I257Impl::new(42, false); let result = a - b; - assert_eq!(result.abs(), 29, "13 - 42 = -29"); + assert_eq!(result.abs(), 29); assert!(result.is_negative(), "13 - 42 -> negative"); // Test subtraction of two negative integers with larger first let a = I257Impl::new(42, true); let b = I257Impl::new(13, true); let result = a - b; - assert_eq!(result.abs(), 29, "-42 - -13 = 29"); + assert_eq!(result.abs(), 29); assert!(result.is_negative(), "-42 - -13 -> negative"); // Test subtraction of two negative integers with larger second let a = I257Impl::new(13, true); let b = I257Impl::new(42, true); let result = a - b; - assert_eq!(result.abs(), 29, "-13 - -42 = 29"); + assert_eq!(result.abs(), 29); assert!(!result.is_negative(), "-13 - -42 -> positive"); // Test subtraction of a positive integer and a negative integer with the same magnitude let a = I257Impl::new(42, false); let b = I257Impl::new(42, true); let result = a - b; - assert_eq!(result.abs(), 84, "42 - -42 = 84"); + assert_eq!(result.abs(), 84); assert!(!result.is_negative(), "42 - -42 -> postive"); // Test subtraction of a negative integer and a positive integer with the same magnitude let a = I257Impl::new(42, true); let b = I257Impl::new(42, false); let result = a - b; - assert_eq!(result.abs(), 84, "-42 - 42 = -84"); + assert_eq!(result.abs(), 84); assert!(result.is_negative(), "-42 - 42 -> negative"); // Test subtraction of a positive integer and a negative integer with different magnitudes let a = I257Impl::new(100, false); let b = I257Impl::new(42, true); let result = a - b; - assert_eq!(result.abs(), 142, "100 - - 42 = 142"); + assert_eq!(result.abs(), 142); assert!(!result.is_negative(), "100 - - 42 -> postive"); // Test subtraction of a negative integer and a positive integer with different magnitudes let a = I257Impl::new(42, true); let b = I257Impl::new(100, false); let result = a - b; - assert_eq!(result.abs(), 142, "-42 - 100 = -142"); + assert_eq!(result.abs(), 142); assert!(result.is_negative(), "-42 - 100 -> negative"); // Test subtraction resulting in zero let a = I257Impl::new(42, false); let b = I257Impl::new(42, false); let result = a - b; - assert_eq!(result.abs(), 0, "42 - 42 = 0"); + assert_eq!(result.abs(), 0); assert!(!result.is_negative(), "42 - 42 -> positive"); } @@ -112,28 +112,28 @@ fn i257_test_mul() { let a = I257Impl::new(10, false); let b = I257Impl::new(5, false); let result = a * b; - assert_eq!(result.abs(), 50, "10 * 5 = 50"); + assert_eq!(result.abs(), 50); assert!(!result.is_negative(), "10 * 5 -> positive"); // Test multiplication of negative integers let a = I257Impl::new(10, true); let b = I257Impl::new(5, true); let result = a * b; - assert_eq!(result.abs(), 50, "-10 * -5 = 50"); + assert_eq!(result.abs(), 50); assert!(!result.is_negative(), "-10 * -5 -> positive"); // Test multiplication of positive and negative integers let a = I257Impl::new(10, false); let b = I257Impl::new(5, true); let result = a * b; - assert_eq!(result.abs(), 50, "10 * -5 = -50"); + assert_eq!(result.abs(), 50); assert!(result.is_negative(), "10 * -5 -> negative"); // Test multiplication by zero let a = I257Impl::new(10, false); let b = I257Impl::new(0, false); let result = a * b; - assert_eq!(result.abs(), 0, "10 * 0 = 0"); + assert_eq!(result.abs(), 0); assert!(!result.is_negative(), "10 * 0 -> positive"); } @@ -149,35 +149,35 @@ fn i257_test_div_no_rem() { let a = I257Impl::new(10, false); let b = I257Impl::new(5, false); let result = a / b; - assert_eq!(result.abs(), 2, "10 // 5 = 2"); + assert_eq!(result.abs(), 2); assert!(!result.is_negative(), "10 // 5 -> positive"); // Test division of negative integers let a = I257Impl::new(10, true); let b = I257Impl::new(5, true); let result = a / b; - assert_eq!(result.abs(), 2, "-10 // -5 = 2"); + assert_eq!(result.abs(), 2); assert!(!result.is_negative(), "-10 // -5 -> positive"); // Test division of positive and negative integers let a = I257Impl::new(10, false); let b = I257Impl::new(5, true); let result = a / b; - assert_eq!(result.abs(), 2, "10 // -5 = -2"); + assert_eq!(result.abs(), 2); assert!(result.is_negative(), "10 // -5 -> negative"); // Test division with a = zero let a = I257Impl::new(0, false); let b = I257Impl::new(10, false); let result = a / b; - assert_eq!(result.abs(), 0, "0 // 10 = 0"); + assert_eq!(result.abs(), 0); assert!(!result.is_negative(), "0 // 10 -> positive"); // Test division with a = zero let a = I257Impl::new(0, false); let b = I257Impl::new(10, false); let result = a / b; - assert_eq!(result.abs(), 0, "0 // 10 = 0"); + assert_eq!(result.abs(), 0); assert!(!result.is_negative(), "0 // 10 -> positive"); } @@ -313,17 +313,17 @@ fn i257_test_equality() { #[test] fn i257_test_div_sign_zero() { let x = I257Impl::new(0, false) / I257Impl::new(3, true); - assert_eq!(x.abs(), 0, "incorrect abs"); + assert_eq!(x.abs(), 0); assert!(!x.is_negative(), "incorrect sign"); } #[test] fn i257_test_into() { let x: i257 = 35.into(); - assert_eq!(x.abs(), 35, "incorrect into value"); + assert_eq!(x.abs(), 35); assert!(!x.is_negative(), "incorrect into sign"); let y: i257 = 258973.into(); - assert_eq!(y.abs(), 258973, "incorrect into value"); + assert_eq!(y.abs(), 258973); assert!(!y.is_negative(), "incorrect into sign"); } diff --git a/packages/math/src/tests/is_power_of_two_test.cairo b/packages/math/src/tests/is_power_of_two_test.cairo index 2d421d6e..26f3ab2f 100644 --- a/packages/math/src/tests/is_power_of_two_test.cairo +++ b/packages/math/src/tests/is_power_of_two_test.cairo @@ -27,5 +27,5 @@ fn is_power_of_two_test_4() { #[test] #[available_gas(200000)] fn is_power_of_two_test_5() { - assert_eq!(is_power_of_two(0), false, "invalid result"); + assert_eq!(is_power_of_two(0), false); } diff --git a/packages/math/src/tests/is_prime_test.cairo b/packages/math/src/tests/is_prime_test.cairo index 64bcee0e..001cf0b2 100644 --- a/packages/math/src/tests/is_prime_test.cairo +++ b/packages/math/src/tests/is_prime_test.cairo @@ -3,23 +3,23 @@ use alexandria_math::is_prime::is_prime; #[test] #[available_gas(200000)] fn is_prime_test_1() { - assert!(is_prime(2, 10), "invalid result"); + assert!(is_prime(2, 10)); } #[test] #[available_gas(200000)] fn is_prime_test_2() { - assert!(!is_prime(0, 10), "invalid result"); + assert!(!is_prime(0, 10)); } #[test] #[available_gas(200000)] fn is_prime_test_3() { - assert!(!is_prime(1, 10), "invalid result"); + assert!(!is_prime(1, 10)); } #[test] #[available_gas(2000000)] fn is_prime_test_4() { - assert!(is_prime(97, 10), "invalid result"); + assert!(is_prime(97, 10)); } diff --git a/packages/math/src/tests/karatsuba_test.cairo b/packages/math/src/tests/karatsuba_test.cairo index 6bd3b69b..1395ca1f 100644 --- a/packages/math/src/tests/karatsuba_test.cairo +++ b/packages/math/src/tests/karatsuba_test.cairo @@ -8,7 +8,7 @@ fn multiply_same_size_positive_number() { let n1 = 31415; let n2 = 31415; let result = 986902225; - assert_eq!(multiply(n1, n2), result, "invalid result"); + assert_eq!(multiply(n1, n2), result); } @@ -18,7 +18,7 @@ fn multiply_distinct_size_positive_number() { let n1 = 10296; let n2 = 25912511; let result = 266795213256; - assert_eq!(multiply(n1, n2), result, "invalid result"); + assert_eq!(multiply(n1, n2), result); } #[test] @@ -28,7 +28,7 @@ fn multiply_by_zero() { let n1 = 10296; let n2 = 0; let result = 0; - assert_eq!(multiply(n1, n2), result, "invalid result"); + assert_eq!(multiply(n1, n2), result); } #[test] @@ -37,5 +37,5 @@ fn multiply_by_number_lt_ten() { let n1 = 1000; let n2 = 2; let result = 2000; - assert_eq!(multiply(n1, n2), result, "invalid result"); + assert_eq!(multiply(n1, n2), result); } diff --git a/packages/math/src/tests/lcm_of_n_numbers_test.cairo b/packages/math/src/tests/lcm_of_n_numbers_test.cairo index 18ef27b0..265fdd77 100644 --- a/packages/math/src/tests/lcm_of_n_numbers_test.cairo +++ b/packages/math/src/tests/lcm_of_n_numbers_test.cairo @@ -12,35 +12,35 @@ impl u128_into_u32 of Into { #[available_gas(1000000000)] fn lcm_test() { let arr = array![2_u128, 4, 6, 8, 10]; - assert_eq!(lcm(arr.span()).unwrap(), 120, "invalid result"); + assert_eq!(lcm(arr.span()).unwrap(), 120); } #[test] #[available_gas(1000000000)] fn lcm_test_tryinto() { let arr = array![2_u32, 4, 6, 8, 10]; - assert_eq!(lcm(arr.span()).unwrap(), 120, "invalid result"); + assert_eq!(lcm(arr.span()).unwrap(), 120); } #[test] #[available_gas(1000000000)] fn lcm_test_inverse() { let arr = array![10_u128, 8, 6, 4, 2]; - assert_eq!(lcm(arr.span()).unwrap(), 120, "invalid result"); + assert_eq!(lcm(arr.span()).unwrap(), 120); } #[test] #[available_gas(1000000000)] fn lcm_test_3() { let arr = array![3_u128, 6, 12, 99]; - assert_eq!(lcm(arr.span()).unwrap(), 396, "invalid result"); + assert_eq!(lcm(arr.span()).unwrap(), 396); } #[test] #[available_gas(1000000000)] fn lcm_test_4() { let arr = array![1_u128, 2, 8, 3]; - assert_eq!(lcm(arr.span()).unwrap(), 24, "invalid result"); + assert_eq!(lcm(arr.span()).unwrap(), 24); } @@ -48,7 +48,7 @@ fn lcm_test_4() { #[available_gas(1000000000)] fn lcm_single_test() { let arr = array![10_u128]; - assert_eq!(lcm(arr.span()).unwrap(), 10, "invalid result"); + assert_eq!(lcm(arr.span()).unwrap(), 10); } #[test] diff --git a/packages/math/src/tests/math_test.cairo b/packages/math/src/tests/math_test.cairo index 3d25be1b..f7a767f3 100644 --- a/packages/math/src/tests/math_test.cairo +++ b/packages/math/src/tests/math_test.cairo @@ -1,149 +1,149 @@ use alexandria_math::{count_digits_of_base, pow, BitShift, BitRotate, WrappingMath}; -use core::integer::BoundedInt; +use core::num::traits::Bounded; // Test power function #[test] #[available_gas(1000000000)] fn test_pow_power_2_all() { - assert_eq!(pow::(2, 0), 1, "0"); - assert_eq!(pow::(2, 1), 2, "1"); - assert_eq!(pow::(2, 2), 4, "2"); - assert_eq!(pow::(2, 3), 8, "3"); - assert_eq!(pow::(2, 4), 16, "4"); - assert_eq!(pow::(2, 5), 32, "5"); - assert_eq!(pow::(2, 6), 64, "6"); - assert_eq!(pow::(2, 7), 128, "7"); - assert_eq!(pow::(2, 8), 256, "8"); - assert_eq!(pow::(2, 9), 512, "9"); - assert_eq!(pow::(2, 10), 1024, "10"); - assert_eq!(pow::(2, 11), 2048, "11"); - assert_eq!(pow::(2, 12), 4096, "12"); - assert_eq!(pow::(2, 13), 8192, "13"); - assert_eq!(pow::(2, 14), 16384, "14"); - assert_eq!(pow::(2, 15), 32768, "15"); - assert_eq!(pow::(2, 16), 65536, "16"); - assert_eq!(pow::(2, 17), 131072, "17"); - assert_eq!(pow::(2, 18), 262144, "18"); - assert_eq!(pow::(2, 19), 524288, "19"); - assert_eq!(pow::(2, 20), 1048576, "20"); - assert_eq!(pow::(2, 21), 2097152, "21"); - assert_eq!(pow::(2, 22), 4194304, "22"); - assert_eq!(pow::(2, 23), 8388608, "23"); - assert_eq!(pow::(2, 24), 16777216, "24"); - assert_eq!(pow::(2, 25), 33554432, "25"); - assert_eq!(pow::(2, 26), 67108864, "26"); - assert_eq!(pow::(2, 27), 134217728, "27"); - assert_eq!(pow::(2, 28), 268435456, "28"); - assert_eq!(pow::(2, 29), 536870912, "29"); - assert_eq!(pow::(2, 30), 1073741824, "30"); - assert_eq!(pow::(2, 31), 2147483648, "31"); - assert_eq!(pow::(2, 32), 4294967296, "32"); - assert_eq!(pow::(2, 33), 8589934592, "33"); - assert_eq!(pow::(2, 34), 17179869184, "34"); - assert_eq!(pow::(2, 35), 34359738368, "35"); - assert_eq!(pow::(2, 36), 68719476736, "36"); - assert_eq!(pow::(2, 37), 137438953472, "37"); - assert_eq!(pow::(2, 38), 274877906944, "38"); - assert_eq!(pow::(2, 39), 549755813888, "39"); - assert_eq!(pow::(2, 40), 1099511627776, "40"); - assert_eq!(pow::(2, 41), 2199023255552, "41"); - assert_eq!(pow::(2, 42), 4398046511104, "42"); - assert_eq!(pow::(2, 43), 8796093022208, "43"); - assert_eq!(pow::(2, 44), 17592186044416, "44"); - assert_eq!(pow::(2, 45), 35184372088832, "45"); - assert_eq!(pow::(2, 46), 70368744177664, "46"); - assert_eq!(pow::(2, 47), 140737488355328, "47"); - assert_eq!(pow::(2, 48), 281474976710656, "48"); - assert_eq!(pow::(2, 49), 562949953421312, "49"); - assert_eq!(pow::(2, 50), 1125899906842624, "50"); - assert_eq!(pow::(2, 51), 2251799813685248, "51"); - assert_eq!(pow::(2, 52), 4503599627370496, "52"); - assert_eq!(pow::(2, 53), 9007199254740992, "53"); - assert_eq!(pow::(2, 54), 18014398509481984, "54"); - assert_eq!(pow::(2, 55), 36028797018963968, "55"); - assert_eq!(pow::(2, 56), 72057594037927936, "56"); - assert_eq!(pow::(2, 57), 144115188075855872, "57"); - assert_eq!(pow::(2, 58), 288230376151711744, "58"); - assert_eq!(pow::(2, 59), 576460752303423488, "59"); - assert_eq!(pow::(2, 60), 1152921504606846976, "60"); - assert_eq!(pow::(2, 61), 2305843009213693952, "61"); - assert_eq!(pow::(2, 62), 4611686018427387904, "62"); - assert_eq!(pow::(2, 63), 9223372036854775808, "63"); - assert_eq!(pow::(2, 64), 18446744073709551616, "64"); - assert_eq!(pow::(2, 65), 36893488147419103232, "65"); - assert_eq!(pow::(2, 66), 73786976294838206464, "66"); - assert_eq!(pow::(2, 67), 147573952589676412928, "67"); - assert_eq!(pow::(2, 68), 295147905179352825856, "68"); - assert_eq!(pow::(2, 69), 590295810358705651712, "69"); - assert_eq!(pow::(2, 70), 1180591620717411303424, "70"); - assert_eq!(pow::(2, 71), 2361183241434822606848, "71"); - assert_eq!(pow::(2, 72), 4722366482869645213696, "72"); - assert_eq!(pow::(2, 73), 9444732965739290427392, "73"); - assert_eq!(pow::(2, 74), 18889465931478580854784, "74"); - assert_eq!(pow::(2, 75), 37778931862957161709568, "75"); - assert_eq!(pow::(2, 76), 75557863725914323419136, "76"); - assert_eq!(pow::(2, 77), 151115727451828646838272, "77"); - assert_eq!(pow::(2, 78), 302231454903657293676544, "78"); - assert_eq!(pow::(2, 79), 604462909807314587353088, "79"); - assert_eq!(pow::(2, 80), 1208925819614629174706176, "80"); - assert_eq!(pow::(2, 81), 2417851639229258349412352, "81"); - assert_eq!(pow::(2, 82), 4835703278458516698824704, "82"); - assert_eq!(pow::(2, 83), 9671406556917033397649408, "83"); - assert_eq!(pow::(2, 84), 19342813113834066795298816, "84"); - assert_eq!(pow::(2, 85), 38685626227668133590597632, "85"); - assert_eq!(pow::(2, 86), 77371252455336267181195264, "86"); - assert_eq!(pow::(2, 87), 154742504910672534362390528, "87"); - assert_eq!(pow::(2, 88), 309485009821345068724781056, "88"); - assert_eq!(pow::(2, 89), 618970019642690137449562112, "89"); - assert_eq!(pow::(2, 90), 1237940039285380274899124224, "90"); - assert_eq!(pow::(2, 91), 2475880078570760549798248448, "91"); - assert_eq!(pow::(2, 92), 4951760157141521099596496896, "92"); - assert_eq!(pow::(2, 93), 9903520314283042199192993792, "93"); - assert_eq!(pow::(2, 94), 19807040628566084398385987584, "94"); - assert_eq!(pow::(2, 95), 39614081257132168796771975168, "95"); - assert_eq!(pow::(2, 96), 79228162514264337593543950336, "96"); - assert_eq!(pow::(2, 97), 158456325028528675187087900672, "97"); - assert_eq!(pow::(2, 98), 316912650057057350374175801344, "98"); - assert_eq!(pow::(2, 99), 633825300114114700748351602688, "99"); - assert_eq!(pow::(2, 100), 1267650600228229401496703205376, "100"); - assert_eq!(pow::(2, 101), 2535301200456458802993406410752, "101"); - assert_eq!(pow::(2, 102), 5070602400912917605986812821504, "102"); - assert_eq!(pow::(2, 103), 10141204801825835211973625643008, "103"); - assert_eq!(pow::(2, 104), 20282409603651670423947251286016, "104"); - assert_eq!(pow::(2, 105), 40564819207303340847894502572032, "105"); - assert_eq!(pow::(2, 106), 81129638414606681695789005144064, "106"); - assert_eq!(pow::(2, 107), 162259276829213363391578010288128, "107"); - assert_eq!(pow::(2, 108), 324518553658426726783156020576256, "108"); - assert_eq!(pow::(2, 109), 649037107316853453566312041152512, "109"); - assert_eq!(pow::(2, 110), 1298074214633706907132624082305024, "110"); - assert_eq!(pow::(2, 111), 2596148429267413814265248164610048, "111"); - assert_eq!(pow::(2, 112), 5192296858534827628530496329220096, "112"); - assert_eq!(pow::(2, 113), 10384593717069655257060992658440192, "113"); - assert_eq!(pow::(2, 114), 20769187434139310514121985316880384, "114"); - assert_eq!(pow::(2, 115), 41538374868278621028243970633760768, "115"); - assert_eq!(pow::(2, 116), 83076749736557242056487941267521536, "116"); - assert_eq!(pow::(2, 117), 166153499473114484112975882535043072, "117"); - assert_eq!(pow::(2, 118), 332306998946228968225951765070086144, "118"); - assert_eq!(pow::(2, 119), 664613997892457936451903530140172288, "119"); - assert_eq!(pow::(2, 120), 1329227995784915872903807060280344576, "120"); - assert_eq!(pow::(2, 121), 2658455991569831745807614120560689152, "121"); - assert_eq!(pow::(2, 122), 5316911983139663491615228241121378304, "122"); - assert_eq!(pow::(2, 123), 10633823966279326983230456482242756608, "123"); - assert_eq!(pow::(2, 124), 21267647932558653966460912964485513216, "124"); - assert_eq!(pow::(2, 125), 42535295865117307932921825928971026432, "125"); - assert_eq!(pow::(2, 126), 85070591730234615865843651857942052864, "126"); - assert_eq!(pow::(2, 127), 170141183460469231731687303715884105728, "127"); + assert_eq!(pow::(2, 0), 1); + assert_eq!(pow::(2, 1), 2); + assert_eq!(pow::(2, 2), 4); + assert_eq!(pow::(2, 3), 8); + assert_eq!(pow::(2, 4), 16); + assert_eq!(pow::(2, 5), 32); + assert_eq!(pow::(2, 6), 64); + assert_eq!(pow::(2, 7), 128); + assert_eq!(pow::(2, 8), 256); + assert_eq!(pow::(2, 9), 512); + assert_eq!(pow::(2, 10), 1024); + assert_eq!(pow::(2, 11), 2048); + assert_eq!(pow::(2, 12), 4096); + assert_eq!(pow::(2, 13), 8192); + assert_eq!(pow::(2, 14), 16384); + assert_eq!(pow::(2, 15), 32768); + assert_eq!(pow::(2, 16), 65536); + assert_eq!(pow::(2, 17), 131072); + assert_eq!(pow::(2, 18), 262144); + assert_eq!(pow::(2, 19), 524288); + assert_eq!(pow::(2, 20), 1048576); + assert_eq!(pow::(2, 21), 2097152); + assert_eq!(pow::(2, 22), 4194304); + assert_eq!(pow::(2, 23), 8388608); + assert_eq!(pow::(2, 24), 16777216); + assert_eq!(pow::(2, 25), 33554432); + assert_eq!(pow::(2, 26), 67108864); + assert_eq!(pow::(2, 27), 134217728); + assert_eq!(pow::(2, 28), 268435456); + assert_eq!(pow::(2, 29), 536870912); + assert_eq!(pow::(2, 30), 1073741824); + assert_eq!(pow::(2, 31), 2147483648); + assert_eq!(pow::(2, 32), 4294967296); + assert_eq!(pow::(2, 33), 8589934592); + assert_eq!(pow::(2, 34), 17179869184); + assert_eq!(pow::(2, 35), 34359738368); + assert_eq!(pow::(2, 36), 68719476736); + assert_eq!(pow::(2, 37), 137438953472); + assert_eq!(pow::(2, 38), 274877906944); + assert_eq!(pow::(2, 39), 549755813888); + assert_eq!(pow::(2, 40), 1099511627776); + assert_eq!(pow::(2, 41), 2199023255552); + assert_eq!(pow::(2, 42), 4398046511104); + assert_eq!(pow::(2, 43), 8796093022208); + assert_eq!(pow::(2, 44), 17592186044416); + assert_eq!(pow::(2, 45), 35184372088832); + assert_eq!(pow::(2, 46), 70368744177664); + assert_eq!(pow::(2, 47), 140737488355328); + assert_eq!(pow::(2, 48), 281474976710656); + assert_eq!(pow::(2, 49), 562949953421312); + assert_eq!(pow::(2, 50), 1125899906842624); + assert_eq!(pow::(2, 51), 2251799813685248); + assert_eq!(pow::(2, 52), 4503599627370496); + assert_eq!(pow::(2, 53), 9007199254740992); + assert_eq!(pow::(2, 54), 18014398509481984); + assert_eq!(pow::(2, 55), 36028797018963968); + assert_eq!(pow::(2, 56), 72057594037927936); + assert_eq!(pow::(2, 57), 144115188075855872); + assert_eq!(pow::(2, 58), 288230376151711744); + assert_eq!(pow::(2, 59), 576460752303423488); + assert_eq!(pow::(2, 60), 1152921504606846976); + assert_eq!(pow::(2, 61), 2305843009213693952); + assert_eq!(pow::(2, 62), 4611686018427387904); + assert_eq!(pow::(2, 63), 9223372036854775808); + assert_eq!(pow::(2, 64), 18446744073709551616); + assert_eq!(pow::(2, 65), 36893488147419103232); + assert_eq!(pow::(2, 66), 73786976294838206464); + assert_eq!(pow::(2, 67), 147573952589676412928); + assert_eq!(pow::(2, 68), 295147905179352825856); + assert_eq!(pow::(2, 69), 590295810358705651712); + assert_eq!(pow::(2, 70), 1180591620717411303424); + assert_eq!(pow::(2, 71), 2361183241434822606848); + assert_eq!(pow::(2, 72), 4722366482869645213696); + assert_eq!(pow::(2, 73), 9444732965739290427392); + assert_eq!(pow::(2, 74), 18889465931478580854784); + assert_eq!(pow::(2, 75), 37778931862957161709568); + assert_eq!(pow::(2, 76), 75557863725914323419136); + assert_eq!(pow::(2, 77), 151115727451828646838272); + assert_eq!(pow::(2, 78), 302231454903657293676544); + assert_eq!(pow::(2, 79), 604462909807314587353088); + assert_eq!(pow::(2, 80), 1208925819614629174706176); + assert_eq!(pow::(2, 81), 2417851639229258349412352); + assert_eq!(pow::(2, 82), 4835703278458516698824704); + assert_eq!(pow::(2, 83), 9671406556917033397649408); + assert_eq!(pow::(2, 84), 19342813113834066795298816); + assert_eq!(pow::(2, 85), 38685626227668133590597632); + assert_eq!(pow::(2, 86), 77371252455336267181195264); + assert_eq!(pow::(2, 87), 154742504910672534362390528); + assert_eq!(pow::(2, 88), 309485009821345068724781056); + assert_eq!(pow::(2, 89), 618970019642690137449562112); + assert_eq!(pow::(2, 90), 1237940039285380274899124224); + assert_eq!(pow::(2, 91), 2475880078570760549798248448); + assert_eq!(pow::(2, 92), 4951760157141521099596496896); + assert_eq!(pow::(2, 93), 9903520314283042199192993792); + assert_eq!(pow::(2, 94), 19807040628566084398385987584); + assert_eq!(pow::(2, 95), 39614081257132168796771975168); + assert_eq!(pow::(2, 96), 79228162514264337593543950336); + assert_eq!(pow::(2, 97), 158456325028528675187087900672); + assert_eq!(pow::(2, 98), 316912650057057350374175801344); + assert_eq!(pow::(2, 99), 633825300114114700748351602688); + assert_eq!(pow::(2, 100), 1267650600228229401496703205376); + assert_eq!(pow::(2, 101), 2535301200456458802993406410752); + assert_eq!(pow::(2, 102), 5070602400912917605986812821504); + assert_eq!(pow::(2, 103), 10141204801825835211973625643008); + assert_eq!(pow::(2, 104), 20282409603651670423947251286016); + assert_eq!(pow::(2, 105), 40564819207303340847894502572032); + assert_eq!(pow::(2, 106), 81129638414606681695789005144064); + assert_eq!(pow::(2, 107), 162259276829213363391578010288128); + assert_eq!(pow::(2, 108), 324518553658426726783156020576256); + assert_eq!(pow::(2, 109), 649037107316853453566312041152512); + assert_eq!(pow::(2, 110), 1298074214633706907132624082305024); + assert_eq!(pow::(2, 111), 2596148429267413814265248164610048); + assert_eq!(pow::(2, 112), 5192296858534827628530496329220096); + assert_eq!(pow::(2, 113), 10384593717069655257060992658440192); + assert_eq!(pow::(2, 114), 20769187434139310514121985316880384); + assert_eq!(pow::(2, 115), 41538374868278621028243970633760768); + assert_eq!(pow::(2, 116), 83076749736557242056487941267521536); + assert_eq!(pow::(2, 117), 166153499473114484112975882535043072); + assert_eq!(pow::(2, 118), 332306998946228968225951765070086144); + assert_eq!(pow::(2, 119), 664613997892457936451903530140172288); + assert_eq!(pow::(2, 120), 1329227995784915872903807060280344576); + assert_eq!(pow::(2, 121), 2658455991569831745807614120560689152); + assert_eq!(pow::(2, 122), 5316911983139663491615228241121378304); + assert_eq!(pow::(2, 123), 10633823966279326983230456482242756608); + assert_eq!(pow::(2, 124), 21267647932558653966460912964485513216); + assert_eq!(pow::(2, 125), 42535295865117307932921825928971026432); + assert_eq!(pow::(2, 126), 85070591730234615865843651857942052864); + assert_eq!(pow::(2, 127), 170141183460469231731687303715884105728); } #[test] #[available_gas(2000000)] fn pow_test() { - assert_eq!(pow::(200, 0), 1, "200^0"); - assert_eq!(pow::(5, 9), 1953125, "5^9"); - assert_eq!(pow::(14, 30), 24201432355484595421941037243826176, "14^30"); - assert_eq!(pow::(3, 8), 6561, "3^8_u128"); - assert_eq!(pow::(3, 8), 6561, "3^8_u256"); + assert_eq!(pow::(200, 0), 1); + assert_eq!(pow::(5, 9), 1953125); + assert_eq!(pow::(14, 30), 24201432355484595421941037243826176); + assert_eq!(pow::(3, 8), 6561); + assert_eq!(pow::(3, 8), 6561); } @@ -151,78 +151,68 @@ fn pow_test() { #[test] #[available_gas(2000000)] fn count_digits_of_base_test() { - assert_eq!(count_digits_of_base(0, 10), 0, "invalid result"); - assert_eq!(count_digits_of_base(2, 10), 1, "invalid result"); - assert_eq!(count_digits_of_base(10, 10), 2, "invalid result"); - assert_eq!(count_digits_of_base(100, 10), 3, "invalid result"); - assert_eq!(count_digits_of_base(0x80, 16), 2, "invalid result"); - assert_eq!(count_digits_of_base(0x800, 16), 3, "invalid result"); - assert_eq!(count_digits_of_base(0x888888888888888888, 16), 18, "invalid result"); + assert_eq!(count_digits_of_base(0, 10), 0); + assert_eq!(count_digits_of_base(2, 10), 1); + assert_eq!(count_digits_of_base(10, 10), 2); + assert_eq!(count_digits_of_base(100, 10), 3); + assert_eq!(count_digits_of_base(0x80, 16), 2); + assert_eq!(count_digits_of_base(0x800, 16), 3); + assert_eq!(count_digits_of_base(0x888888888888888888, 16), 18); } #[test] #[available_gas(2000000)] fn shl_should_not_overflow() { - assert_eq!(BitShift::shl(pow::(2, 7), 1), 0, "invalid result"); - assert_eq!(BitShift::shl(pow::(2, 15), 1), 0, "invalid result"); - assert_eq!(BitShift::shl(pow::(2, 31), 1), 0, "invalid result"); - assert_eq!(BitShift::shl(pow::(2, 63), 1), 0, "invalid result"); - assert_eq!(BitShift::shl(pow::(2, 127), 1), 0, "invalid result"); - assert_eq!(BitShift::shl(pow::(2, 255), 1), 0, "invalid result"); + assert_eq!(BitShift::shl(pow::(2, 7), 1), 0); + assert_eq!(BitShift::shl(pow::(2, 15), 1), 0); + assert_eq!(BitShift::shl(pow::(2, 31), 1), 0); + assert_eq!(BitShift::shl(pow::(2, 63), 1), 0); + assert_eq!(BitShift::shl(pow::(2, 127), 1), 0); + assert_eq!(BitShift::shl(pow::(2, 255), 1), 0); } #[test] #[available_gas(3000000)] fn test_rotl_min() { - assert_eq!(BitRotate::rotate_left(pow::(2, 7) + 1, 1), 3, "invalid result"); - assert_eq!(BitRotate::rotate_left(pow::(2, 15) + 1, 1), 3, "invalid result"); - assert_eq!(BitRotate::rotate_left(pow::(2, 31) + 1, 1), 3, "invalid result"); - assert_eq!(BitRotate::rotate_left(pow::(2, 63) + 1, 1), 3, "invalid result"); - assert_eq!(BitRotate::rotate_left(pow::(2, 127) + 1, 1), 3, "invalid result"); - assert_eq!(BitRotate::rotate_left(pow::(2, 255) + 1, 1), 3, "invalid result"); + assert_eq!(BitRotate::rotate_left(pow::(2, 7) + 1, 1), 3); + assert_eq!(BitRotate::rotate_left(pow::(2, 15) + 1, 1), 3); + assert_eq!(BitRotate::rotate_left(pow::(2, 31) + 1, 1), 3); + assert_eq!(BitRotate::rotate_left(pow::(2, 63) + 1, 1), 3); + assert_eq!(BitRotate::rotate_left(pow::(2, 127) + 1, 1), 3); + assert_eq!(BitRotate::rotate_left(pow::(2, 255) + 1, 1), 3); } #[test] #[available_gas(3000000)] fn test_rotl_max() { - assert_eq!(BitRotate::rotate_left(0b101, 7), pow::(2, 7) + 0b10, "invalid result"); - assert_eq!(BitRotate::rotate_left(0b101, 15), pow::(2, 15) + 0b10, "invalid result"); - assert_eq!(BitRotate::rotate_left(0b101, 31), pow::(2, 31) + 0b10, "invalid result"); - assert_eq!(BitRotate::rotate_left(0b101, 63), pow::(2, 63) + 0b10, "invalid result"); - assert_eq!(BitRotate::rotate_left(0b101, 127), pow::(2, 127) + 0b10, "invalid result"); - assert_eq!(BitRotate::rotate_left(0b101, 255), pow::(2, 255) + 0b10, "invalid result"); + assert_eq!(BitRotate::rotate_left(0b101, 7), pow::(2, 7) + 0b10); + assert_eq!(BitRotate::rotate_left(0b101, 15), pow::(2, 15) + 0b10); + assert_eq!(BitRotate::rotate_left(0b101, 31), pow::(2, 31) + 0b10); + assert_eq!(BitRotate::rotate_left(0b101, 63), pow::(2, 63) + 0b10); + assert_eq!(BitRotate::rotate_left(0b101, 127), pow::(2, 127) + 0b10); + assert_eq!(BitRotate::rotate_left(0b101, 255), pow::(2, 255) + 0b10); } #[test] #[available_gas(4000000)] fn test_rotr_min() { - assert_eq!(BitRotate::rotate_right(pow::(2, 7) + 1, 1), 0b11 * pow(2, 6), "invalid result"); - assert( - BitRotate::rotate_right(pow::(2, 15) + 1, 1) == 0b11 * pow(2, 14), 'invalid result' - ); - assert( - BitRotate::rotate_right(pow::(2, 31) + 1, 1) == 0b11 * pow(2, 30), 'invalid result' - ); - assert( - BitRotate::rotate_right(pow::(2, 63) + 1, 1) == 0b11 * pow(2, 62), 'invalid result' - ); - assert( - BitRotate::rotate_right(pow::(2, 127) + 1, 1) == 0b11 * pow(2, 126), 'invalid result' - ); - assert( - BitRotate::rotate_right(pow::(2, 255) + 1, 1) == 0b11 * pow(2, 254), 'invalid result' - ); + assert_eq!(BitRotate::rotate_right(pow::(2, 7) + 1, 1), 0b11 * pow(2, 6)); + assert_eq!(BitRotate::rotate_right(pow::(2, 15) + 1, 1), 0b11 * pow(2, 14)); + assert_eq!(BitRotate::rotate_right(pow::(2, 31) + 1, 1), 0b11 * pow(2, 30)); + assert_eq!(BitRotate::rotate_right(pow::(2, 63) + 1, 1), 0b11 * pow(2, 62)); + assert_eq!(BitRotate::rotate_right(pow::(2, 127) + 1, 1), 0b11 * pow(2, 126)); + assert_eq!(BitRotate::rotate_right(pow::(2, 255) + 1, 1), 0b11 * pow(2, 254)); } #[test] #[available_gas(2000000)] fn test_rotr_max() { - assert_eq!(BitRotate::rotate_right(0b101_u8, 7), 0b1010, "invalid result"); - assert_eq!(BitRotate::rotate_right(0b101_u16, 15), 0b1010, "invalid result"); - assert_eq!(BitRotate::rotate_right(0b101_u32, 31), 0b1010, "invalid result"); - assert_eq!(BitRotate::rotate_right(0b101_u64, 63), 0b1010, "invalid result"); - assert_eq!(BitRotate::rotate_right(0b101_u128, 127), 0b1010, "invalid result"); - assert_eq!(BitRotate::rotate_right(0b101_u256, 255), 0b1010, "invalid result"); + assert_eq!(BitRotate::rotate_right(0b101_u8, 7), 0b1010); + assert_eq!(BitRotate::rotate_right(0b101_u16, 15), 0b1010); + assert_eq!(BitRotate::rotate_right(0b101_u32, 31), 0b1010); + assert_eq!(BitRotate::rotate_right(0b101_u64, 63), 0b1010); + assert_eq!(BitRotate::rotate_right(0b101_u128, 127), 0b1010); + assert_eq!(BitRotate::rotate_right(0b101_u256, 255), 0b1010); } #[test] @@ -302,105 +292,79 @@ fn test_wrapping_math_non_wrapping() { #[test] fn test_wrapping_math_wrapping() { - assert_eq!(BoundedInt::::max().wrapping_add(1_u8), 0_u8); - assert_eq!(1_u8.wrapping_add(BoundedInt::::max()), 0_u8); - assert_eq!(BoundedInt::::max().wrapping_add(2_u8), 1_u8); - assert_eq!(2_u8.wrapping_add(BoundedInt::::max()), 1_u8); - assert_eq!( - BoundedInt::::max().wrapping_add(BoundedInt::::max()), - BoundedInt::::max() - 1_u8 - ); - assert_eq!(BoundedInt::::min().wrapping_sub(1_u8), BoundedInt::::max()); - assert_eq!(BoundedInt::::min().wrapping_sub(2_u8), BoundedInt::::max() - 1_u8); - assert_eq!(1_u8.wrapping_sub(BoundedInt::::max()), 2_u8); - assert_eq!(0_u8.wrapping_sub(BoundedInt::::max()), 1_u8); - assert_eq!(BoundedInt::::max().wrapping_mul(BoundedInt::::max()), 1_u8); - assert_eq!((BoundedInt::::max() - 1_u8).wrapping_mul(2_u8), BoundedInt::::max() - 3_u8); + assert_eq!(Bounded::::MAX.wrapping_add(1_u8), 0_u8); + assert_eq!(1_u8.wrapping_add(Bounded::::MAX), 0_u8); + assert_eq!(Bounded::::MAX.wrapping_add(2_u8), 1_u8); + assert_eq!(2_u8.wrapping_add(Bounded::::MAX), 1_u8); + assert_eq!(Bounded::::MAX.wrapping_add(Bounded::::MAX), Bounded::::MAX - 1_u8); + assert_eq!(Bounded::::MIN.wrapping_sub(1_u8), Bounded::::MAX); + assert_eq!(Bounded::::MIN.wrapping_sub(2_u8), Bounded::::MAX - 1_u8); + assert_eq!(1_u8.wrapping_sub(Bounded::::MAX), 2_u8); + assert_eq!(0_u8.wrapping_sub(Bounded::::MAX), 1_u8); + assert_eq!(Bounded::::MAX.wrapping_mul(Bounded::::MAX), 1_u8); + assert_eq!((Bounded::::MAX - 1_u8).wrapping_mul(2_u8), Bounded::::MAX - 3_u8); - assert_eq!(BoundedInt::::max().wrapping_add(1_u16), 0_u16); - assert_eq!(1_u16.wrapping_add(BoundedInt::::max()), 0_u16); - assert_eq!(BoundedInt::::max().wrapping_add(2_u16), 1_u16); - assert_eq!(2_u16.wrapping_add(BoundedInt::::max()), 1_u16); - assert_eq!( - BoundedInt::::max().wrapping_add(BoundedInt::::max()), - BoundedInt::::max() - 1_u16 - ); - assert_eq!(BoundedInt::::min().wrapping_sub(1_u16), BoundedInt::::max()); - assert_eq!(BoundedInt::::min().wrapping_sub(2_u16), BoundedInt::::max() - 1_u16); - assert_eq!(1_u16.wrapping_sub(BoundedInt::::max()), 2_u16); - assert_eq!(0_u16.wrapping_sub(BoundedInt::::max()), 1_u16); - assert_eq!(BoundedInt::::max().wrapping_mul(BoundedInt::::max()), 1_u16); - assert_eq!( - (BoundedInt::::max() - 1_u16).wrapping_mul(2_u16), BoundedInt::::max() - 3_u16 - ); + assert_eq!(Bounded::::MAX.wrapping_add(1_u16), 0_u16); + assert_eq!(1_u16.wrapping_add(Bounded::::MAX), 0_u16); + assert_eq!(Bounded::::MAX.wrapping_add(2_u16), 1_u16); + assert_eq!(2_u16.wrapping_add(Bounded::::MAX), 1_u16); + assert_eq!(Bounded::::MAX.wrapping_add(Bounded::::MAX), Bounded::::MAX - 1_u16); + assert_eq!(Bounded::::MIN.wrapping_sub(1_u16), Bounded::::MAX); + assert_eq!(Bounded::::MIN.wrapping_sub(2_u16), Bounded::::MAX - 1_u16); + assert_eq!(1_u16.wrapping_sub(Bounded::::MAX), 2_u16); + assert_eq!(0_u16.wrapping_sub(Bounded::::MAX), 1_u16); + assert_eq!(Bounded::::MAX.wrapping_mul(Bounded::::MAX), 1_u16); + assert_eq!((Bounded::::MAX - 1_u16).wrapping_mul(2_u16), Bounded::::MAX - 3_u16); - assert_eq!(BoundedInt::::max().wrapping_add(1_u32), 0_u32); - assert_eq!(1_u32.wrapping_add(BoundedInt::::max()), 0_u32); - assert_eq!(BoundedInt::::max().wrapping_add(2_u32), 1_u32); - assert_eq!(2_u32.wrapping_add(BoundedInt::::max()), 1_u32); - assert_eq!( - BoundedInt::::max().wrapping_add(BoundedInt::::max()), - BoundedInt::::max() - 1_u32 - ); - assert_eq!(BoundedInt::::min().wrapping_sub(1_u32), BoundedInt::::max()); - assert_eq!(BoundedInt::::min().wrapping_sub(2_u32), BoundedInt::::max() - 1_u32); - assert_eq!(1_u32.wrapping_sub(BoundedInt::::max()), 2_u32); - assert_eq!(0_u32.wrapping_sub(BoundedInt::::max()), 1_u32); - assert_eq!(BoundedInt::::max().wrapping_mul(BoundedInt::::max()), 1_u32); - assert_eq!( - (BoundedInt::::max() - 1_u32).wrapping_mul(2_u32), BoundedInt::::max() - 3_u32 - ); + assert_eq!(Bounded::::MAX.wrapping_add(1_u32), 0_u32); + assert_eq!(1_u32.wrapping_add(Bounded::::MAX), 0_u32); + assert_eq!(Bounded::::MAX.wrapping_add(2_u32), 1_u32); + assert_eq!(2_u32.wrapping_add(Bounded::::MAX), 1_u32); + assert_eq!(Bounded::::MAX.wrapping_add(Bounded::::MAX), Bounded::::MAX - 1_u32); + assert_eq!(Bounded::::MIN.wrapping_sub(1_u32), Bounded::::MAX); + assert_eq!(Bounded::::MIN.wrapping_sub(2_u32), Bounded::::MAX - 1_u32); + assert_eq!(1_u32.wrapping_sub(Bounded::::MAX), 2_u32); + assert_eq!(0_u32.wrapping_sub(Bounded::::MAX), 1_u32); + assert_eq!(Bounded::::MAX.wrapping_mul(Bounded::::MAX), 1_u32); + assert_eq!((Bounded::::MAX - 1_u32).wrapping_mul(2_u32), Bounded::::MAX - 3_u32); - assert_eq!(BoundedInt::::max().wrapping_add(1_u64), 0_u64); - assert_eq!(1_u64.wrapping_add(BoundedInt::::max()), 0_u64); - assert_eq!(BoundedInt::::max().wrapping_add(2_u64), 1_u64); - assert_eq!(2_u64.wrapping_add(BoundedInt::::max()), 1_u64); - assert_eq!( - BoundedInt::::max().wrapping_add(BoundedInt::::max()), - BoundedInt::::max() - 1_u64 - ); - assert_eq!(BoundedInt::::min().wrapping_sub(1_u64), BoundedInt::::max()); - assert_eq!(BoundedInt::::min().wrapping_sub(2_u64), BoundedInt::::max() - 1_u64); - assert_eq!(1_u64.wrapping_sub(BoundedInt::::max()), 2_u64); - assert_eq!(0_u64.wrapping_sub(BoundedInt::::max()), 1_u64); - assert_eq!(BoundedInt::::max().wrapping_mul(BoundedInt::::max()), 1_u64); - assert_eq!( - (BoundedInt::::max() - 1_u64).wrapping_mul(2_u64), BoundedInt::::max() - 3_u64 - ); + assert_eq!(Bounded::::MAX.wrapping_add(1_u64), 0_u64); + assert_eq!(1_u64.wrapping_add(Bounded::::MAX), 0_u64); + assert_eq!(Bounded::::MAX.wrapping_add(2_u64), 1_u64); + assert_eq!(2_u64.wrapping_add(Bounded::::MAX), 1_u64); + assert_eq!(Bounded::::MAX.wrapping_add(Bounded::::MAX), Bounded::::MAX - 1_u64); + assert_eq!(Bounded::::MIN.wrapping_sub(1_u64), Bounded::::MAX); + assert_eq!(Bounded::::MIN.wrapping_sub(2_u64), Bounded::::MAX - 1_u64); + assert_eq!(1_u64.wrapping_sub(Bounded::::MAX), 2_u64); + assert_eq!(0_u64.wrapping_sub(Bounded::::MAX), 1_u64); + assert_eq!(Bounded::::MAX.wrapping_mul(Bounded::::MAX), 1_u64); + assert_eq!((Bounded::::MAX - 1_u64).wrapping_mul(2_u64), Bounded::::MAX - 3_u64); - assert_eq!(BoundedInt::::max().wrapping_add(1_u128), 0_u128); - assert_eq!(1_u128.wrapping_add(BoundedInt::::max()), 0_u128); - assert_eq!(BoundedInt::::max().wrapping_add(2_u128), 1_u128); - assert_eq!(2_u128.wrapping_add(BoundedInt::::max()), 1_u128); - assert_eq!( - BoundedInt::::max().wrapping_add(BoundedInt::::max()), - BoundedInt::::max() - 1_u128 - ); - assert_eq!(BoundedInt::::min().wrapping_sub(1_u128), BoundedInt::::max()); - assert_eq!(BoundedInt::::min().wrapping_sub(2_u128), BoundedInt::::max() - 1_u128); - assert_eq!(1_u128.wrapping_sub(BoundedInt::::max()), 2_u128); - assert_eq!(0_u128.wrapping_sub(BoundedInt::::max()), 1_u128); - assert_eq!(BoundedInt::::max().wrapping_mul(BoundedInt::::max()), 1_u128); + assert_eq!(Bounded::::MAX.wrapping_add(1_u128), 0_u128); + assert_eq!(1_u128.wrapping_add(Bounded::::MAX), 0_u128); + assert_eq!(Bounded::::MAX.wrapping_add(2_u128), 1_u128); + assert_eq!(2_u128.wrapping_add(Bounded::::MAX), 1_u128); assert_eq!( - (BoundedInt::::max() - 1_u128).wrapping_mul(2_u128), - BoundedInt::::max() - 3_u128 + Bounded::::MAX.wrapping_add(Bounded::::MAX), Bounded::::MAX - 1_u128 ); + assert_eq!(Bounded::::MIN.wrapping_sub(1_u128), Bounded::::MAX); + assert_eq!(Bounded::::MIN.wrapping_sub(2_u128), Bounded::::MAX - 1_u128); + assert_eq!(1_u128.wrapping_sub(Bounded::::MAX), 2_u128); + assert_eq!(0_u128.wrapping_sub(Bounded::::MAX), 1_u128); + assert_eq!(Bounded::::MAX.wrapping_mul(Bounded::::MAX), 1_u128); + assert_eq!((Bounded::::MAX - 1_u128).wrapping_mul(2_u128), Bounded::::MAX - 3_u128); - assert_eq!(BoundedInt::::max().wrapping_add(1_u256), 0_u256); - assert_eq!(1_u256.wrapping_add(BoundedInt::::max()), 0_u256); - assert_eq!(BoundedInt::::max().wrapping_add(2_u256), 1_u256); - assert_eq!(2_u256.wrapping_add(BoundedInt::::max()), 1_u256); - assert_eq!( - BoundedInt::::max().wrapping_add(BoundedInt::::max()), - BoundedInt::::max() - 1_u256 - ); - assert_eq!(BoundedInt::::min().wrapping_sub(1_u256), BoundedInt::::max()); - assert_eq!(BoundedInt::::min().wrapping_sub(2_u256), BoundedInt::::max() - 1_u256); - assert_eq!(1_u256.wrapping_sub(BoundedInt::::max()), 2_u256); - assert_eq!(0_u256.wrapping_sub(BoundedInt::::max()), 1_u256); - assert_eq!(BoundedInt::::max().wrapping_mul(BoundedInt::::max()), 1_u256); + assert_eq!(Bounded::::MAX.wrapping_add(1_u256), 0_u256); + assert_eq!(1_u256.wrapping_add(Bounded::::MAX), 0_u256); + assert_eq!(Bounded::::MAX.wrapping_add(2_u256), 1_u256); + assert_eq!(2_u256.wrapping_add(Bounded::::MAX), 1_u256); assert_eq!( - (BoundedInt::::max() - 1_u256).wrapping_mul(2_u256), - BoundedInt::::max() - 3_u256 + Bounded::::MAX.wrapping_add(Bounded::::MAX), Bounded::::MAX - 1_u256 ); + assert_eq!(Bounded::::MIN.wrapping_sub(1_u256), Bounded::::MAX); + assert_eq!(Bounded::::MIN.wrapping_sub(2_u256), Bounded::::MAX - 1_u256); + assert_eq!(1_u256.wrapping_sub(Bounded::::MAX), 2_u256); + assert_eq!(0_u256.wrapping_sub(Bounded::::MAX), 1_u256); + assert_eq!(Bounded::::MAX.wrapping_mul(Bounded::::MAX), 1_u256); + assert_eq!((Bounded::::MAX - 1_u256).wrapping_mul(2_u256), Bounded::::MAX - 3_u256); } diff --git a/packages/math/src/tests/mod_arithmetics_test.cairo b/packages/math/src/tests/mod_arithmetics_test.cairo index a8b52136..e71176fd 100644 --- a/packages/math/src/tests/mod_arithmetics_test.cairo +++ b/packages/math/src/tests/mod_arithmetics_test.cairo @@ -12,113 +12,113 @@ const pow_256_minus_1: u256 = fn add_mod_p_test() { let prime_non_zero = p.try_into().unwrap(); - assert_eq!(add_mod(p, p, prime_non_zero), 0, "Incorrect result"); - assert_eq!(add_mod(p, 1, prime_non_zero), 1, "Incorrect result"); - assert_eq!(add_mod(1, p, prime_non_zero), 1, "Incorrect result"); - assert_eq!(add_mod(10, 30, prime_non_zero), 40, "Incorrect result"); - assert_eq!(add_mod(0, 0, prime_non_zero), 0, "Incorrect result"); - assert_eq!(add_mod(0, 1, prime_non_zero), 1, "Incorrect result"); - assert_eq!(add_mod(1, 0, prime_non_zero), 1, "Incorrect result"); + assert_eq!(add_mod(p, p, prime_non_zero), 0); + assert_eq!(add_mod(p, 1, prime_non_zero), 1); + assert_eq!(add_mod(1, p, prime_non_zero), 1); + assert_eq!(add_mod(10, 30, prime_non_zero), 40); + assert_eq!(add_mod(0, 0, prime_non_zero), 0); + assert_eq!(add_mod(0, 1, prime_non_zero), 1); + assert_eq!(add_mod(1, 0, prime_non_zero), 1); } #[test] #[available_gas(500000000)] fn add_mod_2_test() { - assert_eq!(add_mod(p, 2, 2), 1, "Incorrect result"); - assert_eq!(add_mod(p, 1, 2), 0, "Incorrect result"); + assert_eq!(add_mod(p, 2, 2), 1); + assert_eq!(add_mod(p, 1, 2), 0); } #[test] #[available_gas(500000000)] fn add_mod_1_test() { - assert_eq!(add_mod(p, 2, 1), 0, "Incorrect result"); - assert_eq!(add_mod(p, p, 1), 0, "Incorrect result"); - assert_eq!(add_mod(0, 0, 1), 0, "Incorrect result"); + assert_eq!(add_mod(p, 2, 1), 0); + assert_eq!(add_mod(p, p, 1), 0); + assert_eq!(add_mod(0, 0, 1), 0); } #[test] #[available_gas(500000000)] fn sub_mod_test() { - assert_eq!(sub_mod(p, p, p), 0, "Incorrect result"); - assert_eq!(sub_mod(p, 1, p), (p - 1), "Incorrect result"); - assert_eq!(sub_mod(1, p, p), 1, "Incorrect result"); - assert_eq!(sub_mod(10, 30, p), (p - 30 + 10), "Incorrect result"); - assert_eq!(sub_mod(0, 0, p), 0, "Incorrect result"); - assert_eq!(sub_mod(0, 1, p), (p - 1), "Incorrect result"); - assert_eq!(sub_mod(1, 0, p), 1, "Incorrect result"); - assert_eq!(sub_mod(pow_256_minus_1, 1, p), 36, "Incorrect result"); + assert_eq!(sub_mod(p, p, p), 0); + assert_eq!(sub_mod(p, 1, p), (p - 1)); + assert_eq!(sub_mod(1, p, p), 1); + assert_eq!(sub_mod(10, 30, p), (p - 30 + 10)); + assert_eq!(sub_mod(0, 0, p), 0); + assert_eq!(sub_mod(0, 1, p), (p - 1)); + assert_eq!(sub_mod(1, 0, p), 1); + assert_eq!(sub_mod(pow_256_minus_1, 1, p), 36); } #[test] #[available_gas(500000000)] fn sub_mod_1_test() { - assert_eq!(sub_mod(p, p, 1), 0, "Incorrect result"); - assert_eq!(sub_mod(p, 1, 1), 0, "Incorrect result"); - assert_eq!(sub_mod(1, p, 1), 0, "Incorrect result"); - assert_eq!(sub_mod(10, 30, 1), 0, "Incorrect result"); - assert_eq!(sub_mod(0, 0, 1), 0, "Incorrect result"); - assert_eq!(sub_mod(0, 1, 1), 0, "Incorrect result"); - assert_eq!(sub_mod(1, 0, 1), 0, "Incorrect result"); - assert_eq!(sub_mod(pow_256_minus_1, 1, 1), 0, "Incorrect result"); + assert_eq!(sub_mod(p, p, 1), 0); + assert_eq!(sub_mod(p, 1, 1), 0); + assert_eq!(sub_mod(1, p, 1), 0); + assert_eq!(sub_mod(10, 30, 1), 0); + assert_eq!(sub_mod(0, 0, 1), 0); + assert_eq!(sub_mod(0, 1, 1), 0); + assert_eq!(sub_mod(1, 0, 1), 0); + assert_eq!(sub_mod(pow_256_minus_1, 1, 1), 0); } #[test] #[available_gas(500000000)] fn sub_mod_2_test() { - assert_eq!(sub_mod(p, p, 2), 0, "Incorrect result"); - assert_eq!(sub_mod(p, 1, 2), 0, "Incorrect result"); - assert_eq!(sub_mod(1, p, 2), 0, "Incorrect result"); - assert_eq!(sub_mod(10, 30, 2), 0, "Incorrect result"); - assert_eq!(sub_mod(0, 0, 2), 0, "Incorrect result"); - assert_eq!(sub_mod(0, 1, 2), 1, "Incorrect result"); - assert_eq!(sub_mod(1, 0, 2), 1, "Incorrect result"); - assert_eq!(sub_mod(pow_256_minus_1, 1, 2), 0, "Incorrect result"); + assert_eq!(sub_mod(p, p, 2), 0); + assert_eq!(sub_mod(p, 1, 2), 0); + assert_eq!(sub_mod(1, p, 2), 0); + assert_eq!(sub_mod(10, 30, 2), 0); + assert_eq!(sub_mod(0, 0, 2), 0); + assert_eq!(sub_mod(0, 1, 2), 1); + assert_eq!(sub_mod(1, 0, 2), 1); + assert_eq!(sub_mod(pow_256_minus_1, 1, 2), 0); } #[test] #[available_gas(500000000)] fn mult_mod_test() { let prime_non_zero = p.try_into().unwrap(); - assert_eq!(mult_mod(p, p, prime_non_zero), 0, "Incorrect result"); - assert_eq!(mult_mod(p, 1, prime_non_zero), 0, "Incorrect result"); - assert_eq!(mult_mod(1, p, prime_non_zero), 0, "Incorrect result"); - assert_eq!(mult_mod(10, 30, prime_non_zero), 300, "Incorrect result"); - assert_eq!(mult_mod(0, 0, prime_non_zero), 0, "Incorrect result"); - assert_eq!(mult_mod(0, 1, prime_non_zero), 0, "Incorrect result"); - assert_eq!(mult_mod(1, 0, prime_non_zero), 0, "Incorrect result"); - assert_eq!(mult_mod(pow_256_minus_1, 1, prime_non_zero), 37, "Incorrect result"); + assert_eq!(mult_mod(p, p, prime_non_zero), 0); + assert_eq!(mult_mod(p, 1, prime_non_zero), 0); + assert_eq!(mult_mod(1, p, prime_non_zero), 0); + assert_eq!(mult_mod(10, 30, prime_non_zero), 300); + assert_eq!(mult_mod(0, 0, prime_non_zero), 0); + assert_eq!(mult_mod(0, 1, prime_non_zero), 0); + assert_eq!(mult_mod(1, 0, prime_non_zero), 0); + assert_eq!(mult_mod(pow_256_minus_1, 1, prime_non_zero), 37); } #[test] #[available_gas(500000000)] fn mult_mod_1_test() { - assert_eq!(mult_mod(p, p, 1), 0, "Incorrect result"); - assert_eq!(mult_mod(p, 1, 1), 0, "Incorrect result"); - assert_eq!(mult_mod(1, p, 1), 0, "Incorrect result"); - assert_eq!(mult_mod(10, 30, 1), 0, "Incorrect result"); - assert_eq!(mult_mod(0, 0, 1), 0, "Incorrect result"); - assert_eq!(mult_mod(0, 1, 1), 0, "Incorrect result"); - assert_eq!(mult_mod(1, 0, 1), 0, "Incorrect result"); - assert_eq!(mult_mod(pow_256_minus_1, 1, 1), 0, "Incorrect result"); + assert_eq!(mult_mod(p, p, 1), 0); + assert_eq!(mult_mod(p, 1, 1), 0); + assert_eq!(mult_mod(1, p, 1), 0); + assert_eq!(mult_mod(10, 30, 1), 0); + assert_eq!(mult_mod(0, 0, 1), 0); + assert_eq!(mult_mod(0, 1, 1), 0); + assert_eq!(mult_mod(1, 0, 1), 0); + assert_eq!(mult_mod(pow_256_minus_1, 1, 1), 0); } #[test] #[available_gas(500000000)] fn mult_mod_2_test() { - assert_eq!(mult_mod(p, p, 2), 1, "Incorrect result"); - assert_eq!(mult_mod(p, 1, 2), 1, "Incorrect result"); - assert_eq!(mult_mod(1, p, 2), 1, "Incorrect result"); - assert_eq!(mult_mod(10, 30, 2), 0, "Incorrect result"); - assert_eq!(mult_mod(0, 0, 2), 0, "Incorrect result"); - assert_eq!(mult_mod(0, 1, 2), 0, "Incorrect result"); - assert_eq!(mult_mod(1, 0, 2), 0, "Incorrect result"); - assert_eq!(mult_mod(pow_256_minus_1, 1, 2), 1, "Incorrect result"); + assert_eq!(mult_mod(p, p, 2), 1); + assert_eq!(mult_mod(p, 1, 2), 1); + assert_eq!(mult_mod(1, p, 2), 1); + assert_eq!(mult_mod(10, 30, 2), 0); + assert_eq!(mult_mod(0, 0, 2), 0); + assert_eq!(mult_mod(0, 1, 2), 0); + assert_eq!(mult_mod(1, 0, 2), 0); + assert_eq!(mult_mod(pow_256_minus_1, 1, 2), 1); } #[test] #[available_gas(500000000)] fn sqr_mod_test() { - assert_eq!(sqr_mod(p, 2), 1, "Incorrect result"); + assert_eq!(sqr_mod(p, 2), 1); assert_eq!( sqr_mod(p, pow_256_minus_1.try_into().unwrap()), mult_mod(p, p, pow_256_minus_1.try_into().unwrap()), @@ -137,46 +137,44 @@ fn div_mod_test() { let prime_non_zero = p.try_into().unwrap(); let div_10_30_mod_p = 38597363079105398474523661669562635951089994888546854679819194669304376546633; - assert_eq!(div_mod(p, 1, prime_non_zero), 0, "Incorrect result"); - assert_eq!(div_mod(30, 10, prime_non_zero), 3, "Incorrect result"); - assert_eq!(div_mod(10, 30, prime_non_zero), div_10_30_mod_p, "Incorrect result"); + assert_eq!(div_mod(p, 1, prime_non_zero), 0); + assert_eq!(div_mod(30, 10, prime_non_zero), 3); + assert_eq!(div_mod(10, 30, prime_non_zero), div_10_30_mod_p); } #[test] #[available_gas(500000000)] fn pow_mod_test() { let prime_non_zero = p.try_into().unwrap(); - assert_eq!(pow_mod(2, 4, prime_non_zero), 16, "Incorrect result"); - assert_eq!(pow_mod(2, 256, prime_non_zero), 38, "Incorrect result"); - assert_eq!(pow_mod(2, 260, prime_non_zero), 608, "Incorrect result"); - assert( - pow_mod( - 10, 260, prime_non_zero - ) == 17820046977743035104984469918379927979184337110507416960697246160624073120874, - 'Incorrect result' + assert_eq!(pow_mod(2, 4, prime_non_zero), 16); + assert_eq!(pow_mod(2, 256, prime_non_zero), 38); + assert_eq!(pow_mod(2, 260, prime_non_zero), 608); + assert_eq!( + pow_mod(10, 260, prime_non_zero), + 17820046977743035104984469918379927979184337110507416960697246160624073120874 ); - assert_eq!(pow_mod(4, 174, prime_non_zero), 188166885971377801784666882048, "Incorrect result"); - assert_eq!(pow_mod(100, p, prime_non_zero), 100, "Incorrect result"); + assert_eq!(pow_mod(4, 174, prime_non_zero), 188166885971377801784666882048); + assert_eq!(pow_mod(100, p, prime_non_zero), 100); } #[test] #[available_gas(500000000)] fn pow_mod_1_test() { - assert_eq!(pow_mod(2, 4, 1), 0, "Incorrect result"); - assert_eq!(pow_mod(2, 256, 1), 0, "Incorrect result"); - assert_eq!(pow_mod(2, 260, 1), 0, "Incorrect result"); - assert_eq!(pow_mod(10, 260, 1), 0, "Incorrect result"); - assert_eq!(pow_mod(4, 174, 1), 0, "Incorrect result"); - assert_eq!(pow_mod(100, p, 1), 0, "Incorrect result"); + assert_eq!(pow_mod(2, 4, 1), 0); + assert_eq!(pow_mod(2, 256, 1), 0); + assert_eq!(pow_mod(2, 260, 1), 0); + assert_eq!(pow_mod(10, 260, 1), 0); + assert_eq!(pow_mod(4, 174, 1), 0); + assert_eq!(pow_mod(100, p, 1), 0); } #[test] #[available_gas(500000000)] fn pow_mod_2_test() { - assert_eq!(pow_mod(2, 4, 2), 0, "Incorrect result"); - assert_eq!(pow_mod(2, 256, 2), 0, "Incorrect result"); - assert_eq!(pow_mod(2, 260, 2), 0, "Incorrect result"); - assert_eq!(pow_mod(10, 260, 2), 0, "Incorrect result"); - assert_eq!(pow_mod(4, 174, 2), 0, "Incorrect result"); - assert_eq!(pow_mod(100, p, 2), 0, "Incorrect result"); + assert_eq!(pow_mod(2, 4, 2), 0); + assert_eq!(pow_mod(2, 256, 2), 0); + assert_eq!(pow_mod(2, 260, 2), 0); + assert_eq!(pow_mod(10, 260, 2), 0); + assert_eq!(pow_mod(4, 174, 2), 0); + assert_eq!(pow_mod(100, p, 2), 0); } diff --git a/packages/math/src/tests/perfect_number_test.cairo b/packages/math/src/tests/perfect_number_test.cairo index 10f2dd71..c38d6c72 100644 --- a/packages/math/src/tests/perfect_number_test.cairo +++ b/packages/math/src/tests/perfect_number_test.cairo @@ -32,5 +32,5 @@ fn not_perfect_big_number_test() { #[available_gas(2000000)] fn perfect_numbers_test() { let mut res = perfect_numbers(10); - assert_eq!(res.len(), 1, "invalid result"); + assert_eq!(res.len(), 1); } diff --git a/packages/math/src/tests/sha256_test.cairo b/packages/math/src/tests/sha256_test.cairo index b1aea050..b3a1f04c 100644 --- a/packages/math/src/tests/sha256_test.cairo +++ b/packages/math/src/tests/sha256_test.cairo @@ -7,39 +7,39 @@ fn sha256_empty_test() { let result = sha256::sha256(input); // result should be 0xE3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855 - assert_eq!(result.len(), 32, "invalid result length"); - assert_eq!(*result[0], 0xE3, "invalid result"); - assert_eq!(*result[1], 0xB0, "invalid result"); - assert_eq!(*result[2], 0xC4, "invalid result"); - assert_eq!(*result[3], 0x42, "invalid result"); - assert_eq!(*result[4], 0x98, "invalid result"); - assert_eq!(*result[5], 0xFC, "invalid result"); - assert_eq!(*result[6], 0x1C, "invalid result"); - assert_eq!(*result[7], 0x14, "invalid result"); - assert_eq!(*result[8], 0x9A, "invalid result"); - assert_eq!(*result[9], 0xFB, "invalid result"); - assert_eq!(*result[10], 0xF4, "invalid result"); - assert_eq!(*result[11], 0xC8, "invalid result"); - assert_eq!(*result[12], 0x99, "invalid result"); - assert_eq!(*result[13], 0x6F, "invalid result"); - assert_eq!(*result[14], 0xB9, "invalid result"); - assert_eq!(*result[15], 0x24, "invalid result"); - assert_eq!(*result[16], 0x27, "invalid result"); - assert_eq!(*result[17], 0xAE, "invalid result"); - assert_eq!(*result[18], 0x41, "invalid result"); - assert_eq!(*result[19], 0xE4, "invalid result"); - assert_eq!(*result[20], 0x64, "invalid result"); - assert_eq!(*result[21], 0x9B, "invalid result"); - assert_eq!(*result[22], 0x93, "invalid result"); - assert_eq!(*result[23], 0x4C, "invalid result"); - assert_eq!(*result[24], 0xA4, "invalid result"); - assert_eq!(*result[25], 0x95, "invalid result"); - assert_eq!(*result[26], 0x99, "invalid result"); - assert_eq!(*result[27], 0x1B, "invalid result"); - assert_eq!(*result[28], 0x78, "invalid result"); - assert_eq!(*result[29], 0x52, "invalid result"); - assert_eq!(*result[30], 0xB8, "invalid result"); - assert_eq!(*result[31], 0x55, "invalid result"); + assert_eq!(result.len(), 32); + assert_eq!(*result[0], 0xE3); + assert_eq!(*result[1], 0xB0); + assert_eq!(*result[2], 0xC4); + assert_eq!(*result[3], 0x42); + assert_eq!(*result[4], 0x98); + assert_eq!(*result[5], 0xFC); + assert_eq!(*result[6], 0x1C); + assert_eq!(*result[7], 0x14); + assert_eq!(*result[8], 0x9A); + assert_eq!(*result[9], 0xFB); + assert_eq!(*result[10], 0xF4); + assert_eq!(*result[11], 0xC8); + assert_eq!(*result[12], 0x99); + assert_eq!(*result[13], 0x6F); + assert_eq!(*result[14], 0xB9); + assert_eq!(*result[15], 0x24); + assert_eq!(*result[16], 0x27); + assert_eq!(*result[17], 0xAE); + assert_eq!(*result[18], 0x41); + assert_eq!(*result[19], 0xE4); + assert_eq!(*result[20], 0x64); + assert_eq!(*result[21], 0x9B); + assert_eq!(*result[22], 0x93); + assert_eq!(*result[23], 0x4C); + assert_eq!(*result[24], 0xA4); + assert_eq!(*result[25], 0x95); + assert_eq!(*result[26], 0x99); + assert_eq!(*result[27], 0x1B); + assert_eq!(*result[28], 0x78); + assert_eq!(*result[29], 0x52); + assert_eq!(*result[30], 0xB8); + assert_eq!(*result[31], 0x55); } #[test] @@ -49,46 +49,48 @@ fn sha256_random_data_test() { 0x57, 0x77, 0x71, 0x71, 0x66, 0x50, 0x45, 0x51, 0x51, 0x43, 0x39, 0x48, 0x38 ]; let result = sha256::sha256(input); - assert_eq!(*result[0], 61, "invalid result"); - assert_eq!(*result[1], 226, "invalid result"); - assert_eq!(*result[2], 188, "invalid result"); - assert_eq!(*result[3], 242, "invalid result"); - assert_eq!(*result[4], 118, "invalid result"); - assert_eq!(*result[5], 121, "invalid result"); - assert_eq!(*result[6], 7, "invalid result"); - assert_eq!(*result[7], 225, "invalid result"); - assert_eq!(*result[8], 150, "invalid result"); - assert_eq!(*result[9], 220, "invalid result"); - assert_eq!(*result[10], 105, "invalid result"); - assert_eq!(*result[11], 158, "invalid result"); - assert_eq!(*result[12], 185, "invalid result"); - assert_eq!(*result[13], 180, "invalid result"); - assert_eq!(*result[14], 139, "invalid result"); - assert_eq!(*result[15], 103, "invalid result"); - assert_eq!(*result[16], 221, "invalid result"); - assert_eq!(*result[17], 95, "invalid result"); - assert_eq!(*result[18], 56, "invalid result"); - assert_eq!(*result[19], 88, "invalid result"); - assert_eq!(*result[20], 209, "invalid result"); - assert_eq!(*result[21], 159, "invalid result"); - assert_eq!(*result[22], 255, "invalid result"); - assert_eq!(*result[23], 247, "invalid result"); - assert_eq!(*result[24], 145, "invalid result"); - assert_eq!(*result[25], 146, "invalid result"); - assert_eq!(*result[26], 83, "invalid result"); - assert_eq!(*result[27], 110, "invalid result"); - assert_eq!(*result[28], 185, "invalid result"); - assert_eq!(*result[29], 5, "invalid result"); - assert_eq!(*result[30], 248, "invalid result"); - assert_eq!(*result[31], 15, "invalid result"); + assert_eq!(*result[0], 61); + assert_eq!(*result[1], 226); + assert_eq!(*result[2], 188); + assert_eq!(*result[3], 242); + assert_eq!(*result[4], 118); + assert_eq!(*result[5], 121); + assert_eq!(*result[6], 7); + assert_eq!(*result[7], 225); + assert_eq!(*result[8], 150); + assert_eq!(*result[9], 220); + assert_eq!(*result[10], 105); + assert_eq!(*result[11], 158); + assert_eq!(*result[12], 185); + assert_eq!(*result[13], 180); + assert_eq!(*result[14], 139); + assert_eq!(*result[15], 103); + assert_eq!(*result[16], 221); + assert_eq!(*result[17], 95); + assert_eq!(*result[18], 56); + assert_eq!(*result[19], 88); + assert_eq!(*result[20], 209); + assert_eq!(*result[21], 159); + assert_eq!(*result[22], 255); + assert_eq!(*result[23], 247); + assert_eq!(*result[24], 145); + assert_eq!(*result[25], 146); + assert_eq!(*result[26], 83); + assert_eq!(*result[27], 110); + assert_eq!(*result[28], 185); + assert_eq!(*result[29], 5); + assert_eq!(*result[30], 248); + assert_eq!(*result[31], 15); } #[test] #[available_gas(2000000000)] fn sha256_lorem_ipsum_test() { - // Lorem ipsum, or lsipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs. - // The passage is attributed to an unknown typesetter in the 15th century who is thought to have scrambled parts of - // Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. It usually begins with + // Lorem ipsum, or lsipsum as it is sometimes known, is dummy text used in laying out print, + // graphic or web designs. + // The passage is attributed to an unknown typesetter in the 15th century who is thought to have + // scrambled parts of Cicero's De Finibus Bonorum et Malorum for use in a type specimen book. It + // usually begins with let mut input = array![]; input.append('L'); input.append('o'); @@ -415,39 +417,39 @@ fn sha256_lorem_ipsum_test() { let result = sha256::sha256(input); // result should be 0xD35BF81DDF990122F8B96C7BF88C0737D5080E0C9BC3F7ABF68E6FF0D5F9EA44 - assert_eq!(result.len(), 32, "invalid result length"); - assert_eq!(*result[0], 0xD3, "invalid result"); - assert_eq!(*result[1], 0x5B, "invalid result"); - assert_eq!(*result[2], 0xF8, "invalid result"); - assert_eq!(*result[3], 0x1D, "invalid result"); - assert_eq!(*result[4], 0xDF, "invalid result"); - assert_eq!(*result[5], 0x99, "invalid result"); - assert_eq!(*result[6], 0x01, "invalid result"); - assert_eq!(*result[7], 0x22, "invalid result"); - assert_eq!(*result[8], 0xF8, "invalid result"); - assert_eq!(*result[9], 0xB9, "invalid result"); - assert_eq!(*result[10], 0x6C, "invalid result"); - assert_eq!(*result[11], 0x7B, "invalid result"); - assert_eq!(*result[12], 0xF8, "invalid result"); - assert_eq!(*result[13], 0x8C, "invalid result"); - assert_eq!(*result[14], 0x07, "invalid result"); - assert_eq!(*result[15], 0x37, "invalid result"); - assert_eq!(*result[16], 0xD5, "invalid result"); - assert_eq!(*result[17], 0x08, "invalid result"); - assert_eq!(*result[18], 0x0E, "invalid result"); - assert_eq!(*result[19], 0x0C, "invalid result"); - assert_eq!(*result[20], 0x9B, "invalid result"); - assert_eq!(*result[21], 0xC3, "invalid result"); - assert_eq!(*result[22], 0xF7, "invalid result"); - assert_eq!(*result[23], 0xAB, "invalid result"); - assert_eq!(*result[24], 0xF6, "invalid result"); - assert_eq!(*result[25], 0x8E, "invalid result"); - assert_eq!(*result[26], 0x6F, "invalid result"); - assert_eq!(*result[27], 0xF0, "invalid result"); - assert_eq!(*result[28], 0xD5, "invalid result"); - assert_eq!(*result[29], 0xF9, "invalid result"); - assert_eq!(*result[30], 0xEA, "invalid result"); - assert_eq!(*result[31], 0x44, "invalid result"); + assert_eq!(result.len(), 32); + assert_eq!(*result[0], 0xD3); + assert_eq!(*result[1], 0x5B); + assert_eq!(*result[2], 0xF8); + assert_eq!(*result[3], 0x1D); + assert_eq!(*result[4], 0xDF); + assert_eq!(*result[5], 0x99); + assert_eq!(*result[6], 0x01); + assert_eq!(*result[7], 0x22); + assert_eq!(*result[8], 0xF8); + assert_eq!(*result[9], 0xB9); + assert_eq!(*result[10], 0x6C); + assert_eq!(*result[11], 0x7B); + assert_eq!(*result[12], 0xF8); + assert_eq!(*result[13], 0x8C); + assert_eq!(*result[14], 0x07); + assert_eq!(*result[15], 0x37); + assert_eq!(*result[16], 0xD5); + assert_eq!(*result[17], 0x08); + assert_eq!(*result[18], 0x0E); + assert_eq!(*result[19], 0x0C); + assert_eq!(*result[20], 0x9B); + assert_eq!(*result[21], 0xC3); + assert_eq!(*result[22], 0xF7); + assert_eq!(*result[23], 0xAB); + assert_eq!(*result[24], 0xF6); + assert_eq!(*result[25], 0x8E); + assert_eq!(*result[26], 0x6F); + assert_eq!(*result[27], 0xF0); + assert_eq!(*result[28], 0xD5); + assert_eq!(*result[29], 0xF9); + assert_eq!(*result[30], 0xEA); + assert_eq!(*result[31], 0x44); } #[test] #[available_gas(10_000_000_000)] @@ -665,37 +667,37 @@ fn sha256_url() { let result = sha256::sha256(data); // result should be 0xe5ddd0d703d54d024a1e49cdb614d1f4e9dfa81fff119ca01554ec22d1a45f59 - assert_eq!(result.len(), 32, "invalid result length"); - assert_eq!(*result[0], 0xE5, "invalid result"); - assert_eq!(*result[1], 0xDD, "invalid result"); - assert_eq!(*result[2], 0xD0, "invalid result"); - assert_eq!(*result[3], 0xD7, "invalid result"); - assert_eq!(*result[4], 0x03, "invalid result"); - assert_eq!(*result[5], 0xD5, "invalid result"); - assert_eq!(*result[6], 0x4D, "invalid result"); - assert_eq!(*result[7], 0x02, "invalid result"); - assert_eq!(*result[8], 0x4A, "invalid result"); - assert_eq!(*result[9], 0x1E, "invalid result"); - assert_eq!(*result[10], 0x49, "invalid result"); - assert_eq!(*result[11], 0xCD, "invalid result"); - assert_eq!(*result[12], 0xB6, "invalid result"); - assert_eq!(*result[13], 0x14, "invalid result"); - assert_eq!(*result[14], 0xD1, "invalid result"); - assert_eq!(*result[15], 0xF4, "invalid result"); - assert_eq!(*result[16], 0xE9, "invalid result"); - assert_eq!(*result[17], 0xDF, "invalid result"); - assert_eq!(*result[18], 0xA8, "invalid result"); - assert_eq!(*result[19], 0x1F, "invalid result"); - assert_eq!(*result[20], 0xFF, "invalid result"); - assert_eq!(*result[21], 0x11, "invalid result"); - assert_eq!(*result[22], 0x9C, "invalid result"); - assert_eq!(*result[23], 0xA0, "invalid result"); - assert_eq!(*result[24], 0x15, "invalid result"); - assert_eq!(*result[25], 0x54, "invalid result"); - assert_eq!(*result[26], 0xEC, "invalid result"); - assert_eq!(*result[27], 0x22, "invalid result"); - assert_eq!(*result[28], 0xD1, "invalid result"); - assert_eq!(*result[29], 0xA4, "invalid result"); - assert_eq!(*result[30], 0x5F, "invalid result"); - assert_eq!(*result[31], 0x59, "invalid result"); + assert_eq!(result.len(), 32); + assert_eq!(*result[0], 0xE5); + assert_eq!(*result[1], 0xDD); + assert_eq!(*result[2], 0xD0); + assert_eq!(*result[3], 0xD7); + assert_eq!(*result[4], 0x03); + assert_eq!(*result[5], 0xD5); + assert_eq!(*result[6], 0x4D); + assert_eq!(*result[7], 0x02); + assert_eq!(*result[8], 0x4A); + assert_eq!(*result[9], 0x1E); + assert_eq!(*result[10], 0x49); + assert_eq!(*result[11], 0xCD); + assert_eq!(*result[12], 0xB6); + assert_eq!(*result[13], 0x14); + assert_eq!(*result[14], 0xD1); + assert_eq!(*result[15], 0xF4); + assert_eq!(*result[16], 0xE9); + assert_eq!(*result[17], 0xDF); + assert_eq!(*result[18], 0xA8); + assert_eq!(*result[19], 0x1F); + assert_eq!(*result[20], 0xFF); + assert_eq!(*result[21], 0x11); + assert_eq!(*result[22], 0x9C); + assert_eq!(*result[23], 0xA0); + assert_eq!(*result[24], 0x15); + assert_eq!(*result[25], 0x54); + assert_eq!(*result[26], 0xEC); + assert_eq!(*result[27], 0x22); + assert_eq!(*result[28], 0xD1); + assert_eq!(*result[29], 0xA4); + assert_eq!(*result[30], 0x5F); + assert_eq!(*result[31], 0x59); } diff --git a/packages/math/src/tests/sha512_test.cairo b/packages/math/src/tests/sha512_test.cairo index 0c11c5ee..0cb2142b 100644 --- a/packages/math/src/tests/sha512_test.cairo +++ b/packages/math/src/tests/sha512_test.cairo @@ -333,72 +333,72 @@ fn test_sha512_lorem_ipsum() { let msg = get_lorem_ipsum(); let res = sha512(msg); - assert_eq!(res.len(), 64, "Incorrect hash length"); + assert_eq!(res.len(), 64); - assert_eq!(*res[0], 0xd5, "Incorrect hash value"); - assert_eq!(*res[1], 0xa2, "Incorrect hash value"); - assert_eq!(*res[2], 0xe1, "Incorrect hash value"); - assert_eq!(*res[3], 0x4e, "Incorrect hash value"); - assert_eq!(*res[4], 0xf4, "Incorrect hash value"); - assert_eq!(*res[5], 0x20, "Incorrect hash value"); - assert_eq!(*res[6], 0xf8, "Incorrect hash value"); - assert_eq!(*res[7], 0x2d, "Incorrect hash value"); - assert_eq!(*res[8], 0x68, "Incorrect hash value"); - assert_eq!(*res[9], 0x2b, "Incorrect hash value"); - assert_eq!(*res[10], 0x19, "Incorrect hash value"); - assert_eq!(*res[11], 0xc3, "Incorrect hash value"); - assert_eq!(*res[12], 0xd0, "Incorrect hash value"); - assert_eq!(*res[13], 0x70, "Incorrect hash value"); - assert_eq!(*res[14], 0xf4, "Incorrect hash value"); - assert_eq!(*res[15], 0x81, "Incorrect hash value"); - assert_eq!(*res[16], 0x14, "Incorrect hash value"); - assert_eq!(*res[17], 0xcb, "Incorrect hash value"); - assert_eq!(*res[18], 0xb9, "Incorrect hash value"); - assert_eq!(*res[19], 0x74, "Incorrect hash value"); - assert_eq!(*res[20], 0x7c, "Incorrect hash value"); - assert_eq!(*res[21], 0x7d, "Incorrect hash value"); - assert_eq!(*res[22], 0xb1, "Incorrect hash value"); - assert_eq!(*res[23], 0x15, "Incorrect hash value"); - assert_eq!(*res[24], 0xce, "Incorrect hash value"); - assert_eq!(*res[25], 0xa5, "Incorrect hash value"); - assert_eq!(*res[26], 0x41, "Incorrect hash value"); - assert_eq!(*res[27], 0x3e, "Incorrect hash value"); - assert_eq!(*res[28], 0xf8, "Incorrect hash value"); - assert_eq!(*res[29], 0xcb, "Incorrect hash value"); - assert_eq!(*res[30], 0x8f, "Incorrect hash value"); - assert_eq!(*res[31], 0xba, "Incorrect hash value"); - assert_eq!(*res[32], 0xc6, "Incorrect hash value"); - assert_eq!(*res[33], 0x90, "Incorrect hash value"); - assert_eq!(*res[34], 0x17, "Incorrect hash value"); - assert_eq!(*res[35], 0xc5, "Incorrect hash value"); - assert_eq!(*res[36], 0x17, "Incorrect hash value"); - assert_eq!(*res[37], 0x0f, "Incorrect hash value"); - assert_eq!(*res[38], 0x01, "Incorrect hash value"); - assert_eq!(*res[39], 0xc4, "Incorrect hash value"); - assert_eq!(*res[40], 0x77, "Incorrect hash value"); - assert_eq!(*res[41], 0xb3, "Incorrect hash value"); - assert_eq!(*res[42], 0xdf, "Incorrect hash value"); - assert_eq!(*res[43], 0x3d, "Incorrect hash value"); - assert_eq!(*res[44], 0xfb, "Incorrect hash value"); - assert_eq!(*res[45], 0x34, "Incorrect hash value"); - assert_eq!(*res[46], 0xd3, "Incorrect hash value"); - assert_eq!(*res[47], 0x50, "Incorrect hash value"); - assert_eq!(*res[48], 0x8f, "Incorrect hash value"); - assert_eq!(*res[49], 0xa0, "Incorrect hash value"); - assert_eq!(*res[50], 0xb2, "Incorrect hash value"); - assert_eq!(*res[51], 0xb1, "Incorrect hash value"); - assert_eq!(*res[52], 0x37, "Incorrect hash value"); - assert_eq!(*res[53], 0xd4, "Incorrect hash value"); - assert_eq!(*res[54], 0xcb, "Incorrect hash value"); - assert_eq!(*res[55], 0x54, "Incorrect hash value"); - assert_eq!(*res[56], 0x60, "Incorrect hash value"); - assert_eq!(*res[57], 0x9e, "Incorrect hash value"); - assert_eq!(*res[58], 0x63, "Incorrect hash value"); - assert_eq!(*res[59], 0x3d, "Incorrect hash value"); - assert_eq!(*res[60], 0x14, "Incorrect hash value"); - assert_eq!(*res[61], 0x45, "Incorrect hash value"); - assert_eq!(*res[62], 0x82, "Incorrect hash value"); - assert_eq!(*res[63], 0xc9, "Incorrect hash value"); + assert_eq!(*res[0], 0xd5); + assert_eq!(*res[1], 0xa2); + assert_eq!(*res[2], 0xe1); + assert_eq!(*res[3], 0x4e); + assert_eq!(*res[4], 0xf4); + assert_eq!(*res[5], 0x20); + assert_eq!(*res[6], 0xf8); + assert_eq!(*res[7], 0x2d); + assert_eq!(*res[8], 0x68); + assert_eq!(*res[9], 0x2b); + assert_eq!(*res[10], 0x19); + assert_eq!(*res[11], 0xc3); + assert_eq!(*res[12], 0xd0); + assert_eq!(*res[13], 0x70); + assert_eq!(*res[14], 0xf4); + assert_eq!(*res[15], 0x81); + assert_eq!(*res[16], 0x14); + assert_eq!(*res[17], 0xcb); + assert_eq!(*res[18], 0xb9); + assert_eq!(*res[19], 0x74); + assert_eq!(*res[20], 0x7c); + assert_eq!(*res[21], 0x7d); + assert_eq!(*res[22], 0xb1); + assert_eq!(*res[23], 0x15); + assert_eq!(*res[24], 0xce); + assert_eq!(*res[25], 0xa5); + assert_eq!(*res[26], 0x41); + assert_eq!(*res[27], 0x3e); + assert_eq!(*res[28], 0xf8); + assert_eq!(*res[29], 0xcb); + assert_eq!(*res[30], 0x8f); + assert_eq!(*res[31], 0xba); + assert_eq!(*res[32], 0xc6); + assert_eq!(*res[33], 0x90); + assert_eq!(*res[34], 0x17); + assert_eq!(*res[35], 0xc5); + assert_eq!(*res[36], 0x17); + assert_eq!(*res[37], 0x0f); + assert_eq!(*res[38], 0x01); + assert_eq!(*res[39], 0xc4); + assert_eq!(*res[40], 0x77); + assert_eq!(*res[41], 0xb3); + assert_eq!(*res[42], 0xdf); + assert_eq!(*res[43], 0x3d); + assert_eq!(*res[44], 0xfb); + assert_eq!(*res[45], 0x34); + assert_eq!(*res[46], 0xd3); + assert_eq!(*res[47], 0x50); + assert_eq!(*res[48], 0x8f); + assert_eq!(*res[49], 0xa0); + assert_eq!(*res[50], 0xb2); + assert_eq!(*res[51], 0xb1); + assert_eq!(*res[52], 0x37); + assert_eq!(*res[53], 0xd4); + assert_eq!(*res[54], 0xcb); + assert_eq!(*res[55], 0x54); + assert_eq!(*res[56], 0x60); + assert_eq!(*res[57], 0x9e); + assert_eq!(*res[58], 0x63); + assert_eq!(*res[59], 0x3d); + assert_eq!(*res[60], 0x14); + assert_eq!(*res[61], 0x45); + assert_eq!(*res[62], 0x82); + assert_eq!(*res[63], 0xc9); } #[test] @@ -407,72 +407,72 @@ fn test_sha512_size_one() { let mut arr: Array = array![49]; let mut res = sha512(arr); - assert_eq!(res.len(), 64, "Len should be 64"); + assert_eq!(res.len(), 64); - assert_eq!(*res[0], 0x4d, "invalid value for hash"); - assert_eq!(*res[1], 0xff, "invalid value for hash"); - assert_eq!(*res[2], 0x4e, "invalid value for hash"); - assert_eq!(*res[3], 0xa3, "invalid value for hash"); - assert_eq!(*res[4], 0x40, "invalid value for hash"); - assert_eq!(*res[5], 0xf0, "invalid value for hash"); - assert_eq!(*res[6], 0xa8, "invalid value for hash"); - assert_eq!(*res[7], 0x23, "invalid value for hash"); - assert_eq!(*res[8], 0xf1, "invalid value for hash"); - assert_eq!(*res[9], 0x5d, "invalid value for hash"); - assert_eq!(*res[10], 0x3f, "invalid value for hash"); - assert_eq!(*res[11], 0x4f, "invalid value for hash"); - assert_eq!(*res[12], 0x01, "invalid value for hash"); - assert_eq!(*res[13], 0xab, "invalid value for hash"); - assert_eq!(*res[14], 0x62, "invalid value for hash"); - assert_eq!(*res[15], 0xea, "invalid value for hash"); - assert_eq!(*res[16], 0xe0, "invalid value for hash"); - assert_eq!(*res[17], 0xe5, "invalid value for hash"); - assert_eq!(*res[18], 0xda, "invalid value for hash"); - assert_eq!(*res[19], 0x57, "invalid value for hash"); - assert_eq!(*res[20], 0x9c, "invalid value for hash"); - assert_eq!(*res[21], 0xcb, "invalid value for hash"); - assert_eq!(*res[22], 0x85, "invalid value for hash"); - assert_eq!(*res[23], 0x1f, "invalid value for hash"); - assert_eq!(*res[24], 0x8d, "invalid value for hash"); - assert_eq!(*res[25], 0xb9, "invalid value for hash"); - assert_eq!(*res[26], 0xdf, "invalid value for hash"); - assert_eq!(*res[27], 0xe8, "invalid value for hash"); - assert_eq!(*res[28], 0x4c, "invalid value for hash"); - assert_eq!(*res[29], 0x58, "invalid value for hash"); - assert_eq!(*res[30], 0xb2, "invalid value for hash"); - assert_eq!(*res[31], 0xb3, "invalid value for hash"); - assert_eq!(*res[32], 0x7b, "invalid value for hash"); - assert_eq!(*res[33], 0x89, "invalid value for hash"); - assert_eq!(*res[34], 0x90, "invalid value for hash"); - assert_eq!(*res[35], 0x3a, "invalid value for hash"); - assert_eq!(*res[36], 0x74, "invalid value for hash"); - assert_eq!(*res[37], 0x0e, "invalid value for hash"); - assert_eq!(*res[38], 0x1e, "invalid value for hash"); - assert_eq!(*res[39], 0xe1, "invalid value for hash"); - assert_eq!(*res[40], 0x72, "invalid value for hash"); - assert_eq!(*res[41], 0xda, "invalid value for hash"); - assert_eq!(*res[42], 0x79, "invalid value for hash"); - assert_eq!(*res[43], 0x3a, "invalid value for hash"); - assert_eq!(*res[44], 0x6e, "invalid value for hash"); - assert_eq!(*res[45], 0x79, "invalid value for hash"); - assert_eq!(*res[46], 0xd5, "invalid value for hash"); - assert_eq!(*res[47], 0x60, "invalid value for hash"); - assert_eq!(*res[48], 0xe5, "invalid value for hash"); - assert_eq!(*res[49], 0xf7, "invalid value for hash"); - assert_eq!(*res[50], 0xf9, "invalid value for hash"); - assert_eq!(*res[51], 0xbd, "invalid value for hash"); - assert_eq!(*res[52], 0x05, "invalid value for hash"); - assert_eq!(*res[53], 0x8a, "invalid value for hash"); - assert_eq!(*res[54], 0x12, "invalid value for hash"); - assert_eq!(*res[55], 0xa2, "invalid value for hash"); - assert_eq!(*res[56], 0x80, "invalid value for hash"); - assert_eq!(*res[57], 0x43, "invalid value for hash"); - assert_eq!(*res[58], 0x3e, "invalid value for hash"); - assert_eq!(*res[59], 0xd6, "invalid value for hash"); - assert_eq!(*res[60], 0xfa, "invalid value for hash"); - assert_eq!(*res[61], 0x46, "invalid value for hash"); - assert_eq!(*res[62], 0x51, "invalid value for hash"); - assert_eq!(*res[63], 0x0a, "invalid value for hash"); + assert_eq!(*res[0], 0x4d); + assert_eq!(*res[1], 0xff); + assert_eq!(*res[2], 0x4e); + assert_eq!(*res[3], 0xa3); + assert_eq!(*res[4], 0x40); + assert_eq!(*res[5], 0xf0); + assert_eq!(*res[6], 0xa8); + assert_eq!(*res[7], 0x23); + assert_eq!(*res[8], 0xf1); + assert_eq!(*res[9], 0x5d); + assert_eq!(*res[10], 0x3f); + assert_eq!(*res[11], 0x4f); + assert_eq!(*res[12], 0x01); + assert_eq!(*res[13], 0xab); + assert_eq!(*res[14], 0x62); + assert_eq!(*res[15], 0xea); + assert_eq!(*res[16], 0xe0); + assert_eq!(*res[17], 0xe5); + assert_eq!(*res[18], 0xda); + assert_eq!(*res[19], 0x57); + assert_eq!(*res[20], 0x9c); + assert_eq!(*res[21], 0xcb); + assert_eq!(*res[22], 0x85); + assert_eq!(*res[23], 0x1f); + assert_eq!(*res[24], 0x8d); + assert_eq!(*res[25], 0xb9); + assert_eq!(*res[26], 0xdf); + assert_eq!(*res[27], 0xe8); + assert_eq!(*res[28], 0x4c); + assert_eq!(*res[29], 0x58); + assert_eq!(*res[30], 0xb2); + assert_eq!(*res[31], 0xb3); + assert_eq!(*res[32], 0x7b); + assert_eq!(*res[33], 0x89); + assert_eq!(*res[34], 0x90); + assert_eq!(*res[35], 0x3a); + assert_eq!(*res[36], 0x74); + assert_eq!(*res[37], 0x0e); + assert_eq!(*res[38], 0x1e); + assert_eq!(*res[39], 0xe1); + assert_eq!(*res[40], 0x72); + assert_eq!(*res[41], 0xda); + assert_eq!(*res[42], 0x79); + assert_eq!(*res[43], 0x3a); + assert_eq!(*res[44], 0x6e); + assert_eq!(*res[45], 0x79); + assert_eq!(*res[46], 0xd5); + assert_eq!(*res[47], 0x60); + assert_eq!(*res[48], 0xe5); + assert_eq!(*res[49], 0xf7); + assert_eq!(*res[50], 0xf9); + assert_eq!(*res[51], 0xbd); + assert_eq!(*res[52], 0x05); + assert_eq!(*res[53], 0x8a); + assert_eq!(*res[54], 0x12); + assert_eq!(*res[55], 0xa2); + assert_eq!(*res[56], 0x80); + assert_eq!(*res[57], 0x43); + assert_eq!(*res[58], 0x3e); + assert_eq!(*res[59], 0xd6); + assert_eq!(*res[60], 0xfa); + assert_eq!(*res[61], 0x46); + assert_eq!(*res[62], 0x51); + assert_eq!(*res[63], 0x0a); } #[test] @@ -482,69 +482,69 @@ fn test_size_zero() { let res = sha512(msg); - assert_eq!(res.len(), 64, "Incorrect hash len"); - assert_eq!(*res[0], 0xcf, "Incorrect hash len"); - assert_eq!(*res[1], 0x83, "Incorrect hash len"); - assert_eq!(*res[2], 0xe1, "Incorrect hash len"); - assert_eq!(*res[3], 0x35, "Incorrect hash len"); - assert_eq!(*res[4], 0x7e, "Incorrect hash len"); - assert_eq!(*res[5], 0xef, "Incorrect hash len"); - assert_eq!(*res[6], 0xb8, "Incorrect hash len"); - assert_eq!(*res[7], 0xbd, "Incorrect hash len"); - assert_eq!(*res[8], 0xf1, "Incorrect hash len"); - assert_eq!(*res[9], 0x54, "Incorrect hash len"); - assert_eq!(*res[10], 0x28, "Incorrect hash len"); - assert_eq!(*res[11], 0x50, "Incorrect hash len"); - assert_eq!(*res[12], 0xd6, "Incorrect hash len"); - assert_eq!(*res[13], 0x6d, "Incorrect hash len"); - assert_eq!(*res[14], 0x80, "Incorrect hash len"); - assert_eq!(*res[15], 0x07, "Incorrect hash len"); - assert_eq!(*res[16], 0xd6, "Incorrect hash len"); - assert_eq!(*res[17], 0x20, "Incorrect hash len"); - assert_eq!(*res[18], 0xe4, "Incorrect hash len"); - assert_eq!(*res[19], 0x05, "Incorrect hash len"); - assert_eq!(*res[20], 0x0b, "Incorrect hash len"); - assert_eq!(*res[21], 0x57, "Incorrect hash len"); - assert_eq!(*res[22], 0x15, "Incorrect hash len"); - assert_eq!(*res[23], 0xdc, "Incorrect hash len"); - assert_eq!(*res[24], 0x83, "Incorrect hash len"); - assert_eq!(*res[25], 0xf4, "Incorrect hash len"); - assert_eq!(*res[26], 0xa9, "Incorrect hash len"); - assert_eq!(*res[27], 0x21, "Incorrect hash len"); - assert_eq!(*res[28], 0xd3, "Incorrect hash len"); - assert_eq!(*res[29], 0x6c, "Incorrect hash len"); - assert_eq!(*res[30], 0xe9, "Incorrect hash len"); - assert_eq!(*res[31], 0xce, "Incorrect hash len"); - assert_eq!(*res[32], 0x47, "Incorrect hash len"); - assert_eq!(*res[33], 0xd0, "Incorrect hash len"); - assert_eq!(*res[34], 0xd1, "Incorrect hash len"); - assert_eq!(*res[35], 0x3c, "Incorrect hash len"); - assert_eq!(*res[36], 0x5d, "Incorrect hash len"); - assert_eq!(*res[37], 0x85, "Incorrect hash len"); - assert_eq!(*res[38], 0xf2, "Incorrect hash len"); - assert_eq!(*res[39], 0xb0, "Incorrect hash len"); - assert_eq!(*res[40], 0xff, "Incorrect hash len"); - assert_eq!(*res[41], 0x83, "Incorrect hash len"); - assert_eq!(*res[42], 0x18, "Incorrect hash len"); - assert_eq!(*res[43], 0xd2, "Incorrect hash len"); - assert_eq!(*res[44], 0x87, "Incorrect hash len"); - assert_eq!(*res[45], 0x7e, "Incorrect hash len"); - assert_eq!(*res[46], 0xec, "Incorrect hash len"); - assert_eq!(*res[47], 0x2f, "Incorrect hash len"); - assert_eq!(*res[48], 0x63, "Incorrect hash len"); - assert_eq!(*res[49], 0xb9, "Incorrect hash len"); - assert_eq!(*res[50], 0x31, "Incorrect hash len"); - assert_eq!(*res[51], 0xbd, "Incorrect hash len"); - assert_eq!(*res[52], 0x47, "Incorrect hash len"); - assert_eq!(*res[53], 0x41, "Incorrect hash len"); - assert_eq!(*res[54], 0x7a, "Incorrect hash len"); - assert_eq!(*res[55], 0x81, "Incorrect hash len"); - assert_eq!(*res[56], 0xa5, "Incorrect hash len"); - assert_eq!(*res[57], 0x38, "Incorrect hash len"); - assert_eq!(*res[58], 0x32, "Incorrect hash len"); - assert_eq!(*res[59], 0x7a, "Incorrect hash len"); - assert_eq!(*res[60], 0xf9, "Incorrect hash len"); - assert_eq!(*res[61], 0x27, "Incorrect hash len"); - assert_eq!(*res[62], 0xda, "Incorrect hash len"); - assert_eq!(*res[63], 0x3e, "Incorrect hash len"); + assert_eq!(res.len(), 64); + assert_eq!(*res[0], 0xcf); + assert_eq!(*res[1], 0x83); + assert_eq!(*res[2], 0xe1); + assert_eq!(*res[3], 0x35); + assert_eq!(*res[4], 0x7e); + assert_eq!(*res[5], 0xef); + assert_eq!(*res[6], 0xb8); + assert_eq!(*res[7], 0xbd); + assert_eq!(*res[8], 0xf1); + assert_eq!(*res[9], 0x54); + assert_eq!(*res[10], 0x28); + assert_eq!(*res[11], 0x50); + assert_eq!(*res[12], 0xd6); + assert_eq!(*res[13], 0x6d); + assert_eq!(*res[14], 0x80); + assert_eq!(*res[15], 0x07); + assert_eq!(*res[16], 0xd6); + assert_eq!(*res[17], 0x20); + assert_eq!(*res[18], 0xe4); + assert_eq!(*res[19], 0x05); + assert_eq!(*res[20], 0x0b); + assert_eq!(*res[21], 0x57); + assert_eq!(*res[22], 0x15); + assert_eq!(*res[23], 0xdc); + assert_eq!(*res[24], 0x83); + assert_eq!(*res[25], 0xf4); + assert_eq!(*res[26], 0xa9); + assert_eq!(*res[27], 0x21); + assert_eq!(*res[28], 0xd3); + assert_eq!(*res[29], 0x6c); + assert_eq!(*res[30], 0xe9); + assert_eq!(*res[31], 0xce); + assert_eq!(*res[32], 0x47); + assert_eq!(*res[33], 0xd0); + assert_eq!(*res[34], 0xd1); + assert_eq!(*res[35], 0x3c); + assert_eq!(*res[36], 0x5d); + assert_eq!(*res[37], 0x85); + assert_eq!(*res[38], 0xf2); + assert_eq!(*res[39], 0xb0); + assert_eq!(*res[40], 0xff); + assert_eq!(*res[41], 0x83); + assert_eq!(*res[42], 0x18); + assert_eq!(*res[43], 0xd2); + assert_eq!(*res[44], 0x87); + assert_eq!(*res[45], 0x7e); + assert_eq!(*res[46], 0xec); + assert_eq!(*res[47], 0x2f); + assert_eq!(*res[48], 0x63); + assert_eq!(*res[49], 0xb9); + assert_eq!(*res[50], 0x31); + assert_eq!(*res[51], 0xbd); + assert_eq!(*res[52], 0x47); + assert_eq!(*res[53], 0x41); + assert_eq!(*res[54], 0x7a); + assert_eq!(*res[55], 0x81); + assert_eq!(*res[56], 0xa5); + assert_eq!(*res[57], 0x38); + assert_eq!(*res[58], 0x32); + assert_eq!(*res[59], 0x7a); + assert_eq!(*res[60], 0xf9); + assert_eq!(*res[61], 0x27); + assert_eq!(*res[62], 0xda); + assert_eq!(*res[63], 0x3e); } diff --git a/packages/math/src/tests/test_keccak256.cairo b/packages/math/src/tests/test_keccak256.cairo index 57f1db60..4807da6f 100644 --- a/packages/math/src/tests/test_keccak256.cairo +++ b/packages/math/src/tests/test_keccak256.cairo @@ -8,7 +8,7 @@ fn test_keccak256_empty_bytes() { let hash = keccak256(input.span()); let expected = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; - assert(hash == expected, 'wrong hash value') + assert_eq!(hash, expected) } #[test] @@ -19,7 +19,7 @@ fn test_keccak256_partial_bytes() { let hash = keccak256(input.span()); let expected = 0x51e8babe8b42352100dffa7f7b3843c95245d3d545c6cbf5052e80258ae80627; - assert(hash == expected, 'wrong hash value'); + assert_eq!(hash, expected); } #[test] @@ -64,5 +64,5 @@ fn test_keccak256_full_u256() { let hash = keccak256(input.span()); let expected = 0x98cfb1eca8a71b4a4b1c115f3d5a462296a66487d1d97fb4c47b979c64bde069; - assert(hash == expected, 'wrong hash value'); + assert_eq!(hash, expected); } diff --git a/packages/math/src/tests/u512_arithmetics_test.cairo b/packages/math/src/tests/u512_arithmetics_test.cairo index 894b4941..0bc755a0 100644 --- a/packages/math/src/tests/u512_arithmetics_test.cairo +++ b/packages/math/src/tests/u512_arithmetics_test.cairo @@ -12,39 +12,32 @@ fn mu512(limb0: u128, limb1: u128, limb2: u128, limb3: u128) -> u512 { #[test] fn test_u512_add() { - assert( - u512_add(mu512(1, 2, 3, 4), mu512(5, 6, 7, 8)) == mu512(6, 8, 10, 12), 'incorrect u512 add' - ); - assert( - u512_add(mu512(MAX_128, 1, 2, 3), mu512(4, 5, 6, 7)) == mu512(3, 7, 8, 10), - 'incorrect u512 add' - ); + assert!(u512_add(mu512(1, 2, 3, 4), mu512(5, 6, 7, 8)) == mu512(6, 8, 10, 12)); + assert!(u512_add(mu512(MAX_128, 1, 2, 3), mu512(4, 5, 6, 7)) == mu512(3, 7, 8, 10)); } #[test] fn test_u512_sub() { let sub0 = u512_sub(mu512(5, 6, 7, 8), mu512(1, 2, 3, 4)); - assert(sub0 == mu512(4, 4, 4, 4), 'incorrect u512 sub'); + assert!(sub0 == mu512(4, 4, 4, 4)); let sub1 = u512_sub(mu512(3, 2, 1, MAX_128,), mu512(7, 6, 5, 4)); - assert( + assert!( sub1 == mu512( 0xfffffffffffffffffffffffffffffffc, 0xfffffffffffffffffffffffffffffffb, 0xfffffffffffffffffffffffffffffffb, 0xfffffffffffffffffffffffffffffffa - ), - 'incorrect u512 sub1' + ) ); let sub2 = u512_sub(mu512(3, 2, 1, 1), mu512(7, 6, 5, 0)); - assert( + assert!( sub2 == mu512( 0xfffffffffffffffffffffffffffffffc, 0xfffffffffffffffffffffffffffffffb, 0xfffffffffffffffffffffffffffffffb, 0 - ), - 'incorrect u512 sub2' + ) ); } diff --git a/packages/math/src/tests/wad_ray_math_test.cairo b/packages/math/src/tests/wad_ray_math_test.cairo index 9ae466a2..d105b400 100644 --- a/packages/math/src/tests/wad_ray_math_test.cairo +++ b/packages/math/src/tests/wad_ray_math_test.cairo @@ -9,7 +9,7 @@ use alexandria_math::{pow}; fn test_wad_to_ray_conversion() { let a = 5 * pow(10, 17); // 0.5e18 let expected = 5 * pow(10, 26); // 0.5e27 - assert_eq!(wad_to_ray(a), expected, "Wrong wad_to_ray conversion"); + assert_eq!(wad_to_ray(a), expected); } #[test] @@ -17,7 +17,7 @@ fn test_wad_to_ray_conversion() { fn test_ray_to_wad_conversion() { let a = 5 * pow(10, 26); // 0.5e27 let expected = 5 * pow(10, 17); // 0.5e18 - assert_eq!(ray_to_wad(a), expected, "Wrong ray_to_wad conversion"); + assert_eq!(ray_to_wad(a), expected); } // wad @@ -31,19 +31,19 @@ fn test_revertWhen_wad_mul_overflow() { #[test] #[available_gas(2000000)] fn test_wad_mul_trivial() { - assert_eq!(wad_mul(pow(2, 128) - 1, wad()), pow(2, 128) - 1, "Wrong result: 2**128 -1 * 1e18"); - assert_eq!(wad_mul(0, 0), 0, "Wrong result: 0 * 0"); - assert_eq!(wad_mul(0, wad()), 0, "Wrong result: 0 * 1e18"); - assert_eq!(wad_mul(wad(), 0), 0, "Wrong result: 1e18 * 0"); - assert_eq!(wad_mul(wad(), wad()), wad(), "Wrong result: 1e18 * 1e18 "); + assert_eq!(wad_mul(pow(2, 128) - 1, wad()), pow(2, 128) - 1); + assert_eq!(wad_mul(0, 0), 0); + assert_eq!(wad_mul(0, wad()), 0); + assert_eq!(wad_mul(wad(), 0), 0); + assert_eq!(wad_mul(wad(), wad()), wad()); } #[test] #[available_gas(2000000)] fn test_wad_mul_fractions() { let val: u256 = 2 * pow(10, 17); // 0.2e18 - assert_eq!(wad_mul(wad(), val), val, "Wrong result: 1e18 * 0.2e18"); - assert_eq!(wad_mul(wad() * 2, val), val * 2, "Wrong result: 2e18 * 0.2e18"); + assert_eq!(wad_mul(wad(), val), val); + assert_eq!(wad_mul(wad() * 2, val), val * 2); } #[test] @@ -56,16 +56,16 @@ fn test_revertWhen_wad_div_zero() { #[test] #[available_gas(3000000)] fn test_wad_div_trivial() { - assert_eq!(wad_div(pow(2, 128) - 1, wad()), pow(2, 128) - 1, "Wrong result: 2**128 -1 / 1e18"); - assert_eq!(wad_div(0, pow(2, 128) - 1), 0, "Wrong result: 0 / 2**128 -1"); - assert_eq!(wad_div(wad(), wad()), wad(), "Wrong result: 1e18 / 1e18"); + assert_eq!(wad_div(pow(2, 128) - 1, wad()), pow(2, 128) - 1); + assert_eq!(wad_div(0, pow(2, 128) - 1), 0); + assert_eq!(wad_div(wad(), wad()), wad()); } #[test] #[available_gas(2000000)] fn test_wad_div_fractions() { - assert_eq!(wad_div(wad() * 2, wad() * 2), wad(), "Wrong result: 2e18 / 2e18"); - assert_eq!(wad_div(wad(), wad() * 2), half_wad(), "Wrong result: 1e18 / 2e18"); + assert_eq!(wad_div(wad() * 2, wad() * 2), wad()); + assert_eq!(wad_div(wad(), wad() * 2), half_wad()); } #[test] @@ -74,8 +74,8 @@ fn test_wad_mul_rounding() { let a = 950000000000005647; let b = 1000000000; let expected = 950000000; - assert_eq!(wad_mul(a, b), expected, "Wrong rounding down: a * b"); - assert_eq!(wad_mul(b, a), expected, "Wrong rounding down: b * a"); + assert_eq!(wad_mul(a, b), expected); + assert_eq!(wad_mul(b, a), expected); } #[test] @@ -84,8 +84,8 @@ fn test_wad_mul_rounding_up() { let a = pow(10, 18) - 1; let b = 2; let expected = 2; - assert_eq!(wad_mul(a, b), expected, "Wrong rounding: a * b"); - assert_eq!(wad_mul(b, a), expected, "Wrong rounding: b * a"); + assert_eq!(wad_mul(a, b), expected); + assert_eq!(wad_mul(b, a), expected); } @@ -100,19 +100,19 @@ fn test_revertWhen_ray_mul_overflow() { #[test] #[available_gas(2000000)] fn test_ray_mul_trivial() { - assert_eq!(ray_mul(pow(2, 128) - 1, ray()), pow(2, 128) - 1, "Wrong result: 2**128 -1 * 1e27"); - assert_eq!(ray_mul(0, 0), 0, "Wrong result: 0 * 0"); - assert_eq!(ray_mul(0, ray()), 0, "Wrong result: 0 * 1e27"); - assert_eq!(ray_mul(ray(), 0), 0, "Wrong result: 1e27 * 0"); - assert_eq!(ray_mul(ray(), ray()), ray(), "Wrong result: 1e27 * 1e27 "); + assert_eq!(ray_mul(pow(2, 128) - 1, ray()), pow(2, 128) - 1); + assert_eq!(ray_mul(0, 0), 0); + assert_eq!(ray_mul(0, ray()), 0); + assert_eq!(ray_mul(ray(), 0), 0); + assert_eq!(ray_mul(ray(), ray()), ray()); } #[test] #[available_gas(2000000)] fn test_ray_mul_fractions() { let val: u256 = 2 * pow(10, 26); // 0.2e27 - assert_eq!(ray_mul(ray(), val), val, "Wrong result: 1e27 * 0.2e27"); - assert_eq!(ray_mul(ray() * 2, val), val * 2, "Wrong result: 2e27 * 0.2e27"); + assert_eq!(ray_mul(ray(), val), val); + assert_eq!(ray_mul(ray() * 2, val), val * 2); } #[test] @@ -125,16 +125,16 @@ fn test_revertWhen_ray_div_zero() { #[test] #[available_gas(3000000)] fn test_ray_div_trivial() { - assert_eq!(ray_div(pow(2, 128) - 1, ray()), pow(2, 128) - 1, "Wrong result: 2**128 -1 / 1e27"); - assert_eq!(ray_div(0, pow(2, 128) - 1), 0, "Wrong result: 0 / 2**128 -1"); - assert_eq!(ray_div(ray(), ray()), ray(), "Wrong result: 1e27 / 1e27"); + assert_eq!(ray_div(pow(2, 128) - 1, ray()), pow(2, 128) - 1); + assert_eq!(ray_div(0, pow(2, 128) - 1), 0); + assert_eq!(ray_div(ray(), ray()), ray()); } #[test] #[available_gas(2000000)] fn test_ray_div_fractions() { - assert_eq!(ray_div(ray() * 2, ray() * 2), ray(), "Wrong result: 2e27 / 2e27"); - assert_eq!(ray_div(ray(), ray() * 2), half_ray(), "Wrong result: 1e27 / 2e27"); + assert_eq!(ray_div(ray() * 2, ray() * 2), ray()); + assert_eq!(ray_div(ray(), ray() * 2), half_ray()); } #[test] @@ -143,8 +143,8 @@ fn test_ray_mul_rounding() { let a = pow(10, 18); let b = 95 * pow(10, 26) + 5647; let expected = 95 * pow(10, 17); - assert_eq!(ray_mul(a, b), expected, "Wrong rounding down: a * b"); - assert_eq!(ray_mul(b, a), expected, "Wrong rounding down: b * a"); + assert_eq!(ray_mul(a, b), expected); + assert_eq!(ray_mul(b, a), expected); } @@ -154,6 +154,6 @@ fn test_ray_mul_rounding_up() { let a = pow(10, 27) - 1; let b = 2; let expected = 2; - assert_eq!(ray_mul(a, b), expected, "Wrong rounding up: a * b"); - assert_eq!(ray_mul(b, a), expected, "Wrong rounding up: b * a"); + assert_eq!(ray_mul(a, b), expected); + assert_eq!(ray_mul(b, a), expected); } diff --git a/packages/math/src/tests/zellers_congruence_test.cairo b/packages/math/src/tests/zellers_congruence_test.cairo index 77943d0c..8f1a64a1 100644 --- a/packages/math/src/tests/zellers_congruence_test.cairo +++ b/packages/math/src/tests/zellers_congruence_test.cairo @@ -9,7 +9,7 @@ fn test_case(day: u128, month: u128, year: u128, expected: u128, error_expected: } // Otherwise, unwrap the day and check it else { let day = day.unwrap(); - assert_eq!(day, expected, "day is invalid"); + assert_eq!(day, expected); } } diff --git a/packages/math/src/trigonometry.cairo b/packages/math/src/trigonometry.cairo index f5a14789..f49ede6f 100644 --- a/packages/math/src/trigonometry.cairo +++ b/packages/math/src/trigonometry.cairo @@ -1,4 +1,42 @@ use core::traits::TryInto; +const BASE_I64: i64 = 100000000; +const FAST_I90: i64 = 90 * BASE_I64; + +const BASE: u64 = 100000000; +const FAST_360: u64 = 360 * BASE; +const FAST_180: u64 = 180 * BASE; +const FAST_90: u64 = 90 * BASE; +const FAST_10: u64 = 10 * BASE; + +const sin_table: [ + u64 + ; 10] = [ + 0_u64, // sin(0) + 17364818_u64, // sin(10) + 34202014_u64, // sin(20) + 50000000_u64, // sin(30) + 64278761_u64, // sin(40) + 76604444_u64, // sin(50) + 86602540_u64, // sin(60) + 93969262_u64, // sin(70) + 98480775_u64, // sin(80) + 100000000_u64 // sin(90) +]; + +const cos_table: [ + u64 + ; 10] = [ + 100000000_u64, // cos(0) + 99984769_u64, // cos(1) + 99939082_u64, // cos(2) + 99862953_u64, // cos(3) + 99756405_u64, // cos(4) + 99619470_u64, // cos(5) + 99452190_u64, // cos(6) + 99254615_u64, // cos(7) + 99026807_u64, // cos(8) + 98768834_u64, // cos(9) +]; // Calculate fast sin(x) // Since there is no float in cairo, we multiply every number by 1e8 @@ -10,51 +48,26 @@ use core::traits::TryInto; // # Example // * fast_sin(3000000000) = (true, 50000000) pub fn fast_sin_inner(x: u64) -> (bool, u64) { - let multipier = 100000000_u64; let hollyst: u64 = 1745329_u64; - let sin_table = array![ - 0_u64, // sin(0) - 17364818_u64, // sin(10) - 34202014_u64, // sin(20) - 50000000_u64, // sin(30) - 64278761_u64, // sin(40) - 76604444_u64, // sin(50) - 86602540_u64, // sin(60) - 93969262_u64, // sin(70) - 98480775_u64, // sin(80) - 100000000_u64 // sin(90) - ]; - let cos_table = array![ - 100000000_u64, // cos(0) - 99984769_u64, // cos(1) - 99939082_u64, // cos(2) - 99862953_u64, // cos(3) - 99756405_u64, // cos(4) - 99619470_u64, // cos(5) - 99452190_u64, // cos(6) - 99254615_u64, // cos(7) - 99026807_u64, // cos(8) - 98768834_u64, // cos(9) - ]; - let mut a = x % consteval_int!(360_u64 * 100000000_u64); + let mut a = x % FAST_360; let mut sig = true; - if a > consteval_int!(180_u64 * 100000000_u64) { + if a > FAST_180 { sig = false; - a = a - consteval_int!(180_u64 * 100000000_u64); + a = a - FAST_180; } - if a > consteval_int!(90_u64 * 100000000_u64) { - a = consteval_int!(180_u64 * 100000000_u64) - a; + if a > FAST_90 { + a = FAST_180 - a; } - let i: usize = (a / consteval_int!(10_u64 * 100000000_u64)).try_into().unwrap(); - let j = a - i.into() * consteval_int!(10_u64 * 100000000_u64); - let int_j: usize = (j / multipier).try_into().unwrap(); + let i: usize = (a / FAST_10).try_into().unwrap(); + let j = a - i.into() * FAST_10; + let int_j: usize = (j / BASE).try_into().unwrap(); - let y = *sin_table[i] * *cos_table[int_j] / multipier - + ((j * hollyst) / multipier) * *sin_table[9 - - i] / multipier; + let y = *sin_table.span()[i] * *cos_table.span()[int_j] / BASE + + ((j * hollyst) / BASE) * *sin_table.span()[9 + - i] / BASE; return (sig, y); } @@ -95,7 +108,7 @@ pub fn fast_sin(x: i64) -> i64 { // # Example // * fast_cos(6000000000) = 50000000 pub fn fast_cos(x: i64) -> i64 { - let mut a = x + consteval_int!(90_i64 * 100000000_i64); + let mut a = x + FAST_I90; if x < 0 { a = -x; } @@ -118,20 +131,19 @@ pub fn fast_cos(x: i64) -> i64 { // # Example // * fast_tan(4500000000) = 100000000 pub fn fast_tan(x: i64) -> i64 { - let multipier = 100000000_u64; let mut a = x; if x < 0 { a = -x; } let input_sin: u64 = a.try_into().unwrap(); - let input_cos: u64 = (a + consteval_int!(90_i64 * 100000000_i64)).try_into().unwrap(); + let input_cos: u64 = (a + FAST_I90).try_into().unwrap(); let (sig_sin, result_u64_sin) = fast_sin_inner(input_sin); let (sig_cos, result_u64_cos) = fast_sin_inner(input_cos); let mut sig = sig_sin || sig_cos; if x < 0 { sig = !sig; } - let result_u64 = result_u64_sin * multipier / result_u64_cos; + let result_u64 = result_u64_sin * BASE / result_u64_cos; let result: i64 = result_u64.try_into().unwrap(); if sig { return result; diff --git a/packages/math/src/u512_arithmetics.cairo b/packages/math/src/u512_arithmetics.cairo index 6bdfa0af..1544c52f 100644 --- a/packages/math/src/u512_arithmetics.cairo +++ b/packages/math/src/u512_arithmetics.cairo @@ -1,9 +1,9 @@ use core::integer::u512; -use core::integer::{u128_overflowing_add, u128_overflowing_sub}; +use core::num::traits::{OverflowingAdd, OverflowingSub}; use core::result::ResultTrait; -pub fn u256_overflow_add(lhs: u256, rhs: u256) -> Result implicits(RangeCheck) nopanic { - let (sum, overflow) = core::integer::u256_overflowing_add(lhs, rhs); +fn u256_overflow_add(lhs: u256, rhs: u256) -> Result implicits(RangeCheck) { + let (sum, overflow) = lhs.overflowing_add(rhs); if overflow { Result::Err(sum) } else { @@ -11,8 +11,8 @@ pub fn u256_overflow_add(lhs: u256, rhs: u256) -> Result implicits(R } } -pub fn u256_overflow_sub(lhs: u256, rhs: u256) -> Result implicits(RangeCheck) nopanic { - let (sum, overflow) = core::integer::u256_overflow_sub(lhs, rhs); +fn u256_overflow_sub(lhs: u256, rhs: u256) -> Result implicits(RangeCheck) { + let (sum, overflow) = lhs.overflowing_sub(rhs); if overflow { Result::Err(sum) } else { @@ -48,14 +48,17 @@ pub fn u512_add(lhs: u512, rhs: u512) -> u512 { Result::Err(u256 { low: limb0, high: limb1 }) => { // Try to move overflow to limb2 - return match u128_overflowing_add(limb2, 1_u128) { - Result::Ok(limb2) => u512 { limb0, limb1, limb2, limb3 }, - Result::Err(limb2) => { - // Try to move overflow to limb3 - let limb3 = u128_overflowing_add(limb3, 1_u128).expect('u512 add overflow'); - u512 { limb0, limb1, limb2, limb3 } - }, - }; + let (limb2, did_overflow) = limb2.overflowing_add(1_u128); + if did_overflow { + // Try to move overflow to limb3 + let (limb3, did_overflow) = limb3.overflowing_add(1_u128); + if did_overflow { + panic!("u512 add overflow"); + } + u512 { limb0, limb1, limb2, limb3 } + } else { + u512 { limb0, limb1, limb2, limb3 } + } }, } } @@ -74,14 +77,17 @@ pub fn u512_sub(lhs: u512, rhs: u512) -> u512 { Result::Err(u256 { low: limb0, high: limb1 }) => { // Try to move overflow to limb2 - return match u128_overflowing_sub(limb2, 1_u128) { - Result::Ok(limb2) => u512 { limb0, limb1, limb2, limb3 }, - Result::Err(limb2) => { - // Try to move overflow to limb3 - let limb3 = u128_overflowing_sub(limb3, 1_u128).expect('u512 sub overflow'); - u512 { limb0, limb1, limb2, limb3 } - }, - }; + let (limb2, did_overflow) = limb2.overflowing_sub(1_u128); + if did_overflow { + // Try to move overflow to limb3 + let (limb3, did_overflow) = limb3.overflowing_sub(1_u128); + if did_overflow { + panic!("u512 sub overflow"); + } + u512 { limb0, limb1, limb2, limb3 } + } else { + u512 { limb0, limb1, limb2, limb3 } + } }, } } diff --git a/packages/math/src/wad_ray_math.cairo b/packages/math/src/wad_ray_math.cairo index 140af871..1c231b1e 100644 --- a/packages/math/src/wad_ray_math.cairo +++ b/packages/math/src/wad_ray_math.cairo @@ -1,6 +1,6 @@ /// Provides functions to perform calculations with Wad and Ray units -/// @dev Provides mul and div function for wads (decimal numbers with 18 digits of precision) and rays (decimal numbers -/// with 27 digits of precision) +/// @dev Provides mul and div function for wads (decimal numbers with 18 digits of precision) and +/// rays (decimal numbers with 27 digits of precision) /// Operations are rounded. If a value is >=.5, will be rounded up, otherwise rounded down. /// https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/libraries/math/WadRayMath.sol diff --git a/packages/math/src/zellers_congruence.cairo b/packages/math/src/zellers_congruence.cairo index 0c874af4..d632bcac 100644 --- a/packages/math/src/zellers_congruence.cairo +++ b/packages/math/src/zellers_congruence.cairo @@ -3,7 +3,8 @@ //! It can be considered to be based on the conversion between Julian day and the calendar date. /// Compute the day of the week for the given Gregorian date. -/// The returned value is an integer in the range 0 to 6, where 0 is Saturday, 1 is Sunday, 2 is Monday, and so on. +/// The returned value is an integer in the range 0 to 6, where 0 is Saturday, 1 is Sunday, 2 is +/// Monday, and so on. /// # Arguments /// * `date` - The date of the month /// * `month` - The month of the year diff --git a/packages/merkle_tree/Scarb.toml b/packages/merkle_tree/Scarb.toml index a7ac76f7..29fa0ab8 100644 --- a/packages/merkle_tree/Scarb.toml +++ b/packages/merkle_tree/Scarb.toml @@ -7,3 +7,6 @@ edition = "2023_11" [tool] fmt.workspace = true + +[dev-dependencies] +cairo_test.workspace = true \ No newline at end of file diff --git a/packages/merkle_tree/src/merkle_tree.cairo b/packages/merkle_tree/src/merkle_tree.cairo index c723c8ff..7b348e30 100644 --- a/packages/merkle_tree/src/merkle_tree.cairo +++ b/packages/merkle_tree/src/merkle_tree.cairo @@ -4,7 +4,8 @@ //! //! ``` //! // This version uses the pedersen hash method because the PedersenHasherImpl is in the scope. -//! use alexandria_data_structures::merkle_tree::{Hasher, MerkleTree, pedersen::PedersenHasherImpl, MerkleTreeTrait}; +//! use alexandria_data_structures::merkle_tree::{Hasher, MerkleTree, pedersen::PedersenHasherImpl, +//! MerkleTreeTrait}; //! //! // Create a new merkle tree instance. //! let mut merkle_tree: MerkleTree = MerkleTreeTrait::new(); @@ -15,7 +16,8 @@ //! //! ``` //! // This version uses the poseidon hash method because the PoseidonHasherImpl is in the scope. -//! use alexandria_data_structures::merkle_tree::{ Hasher, MerkleTree, poseidon::PoseidonHasherImpl, MerkleTreeTrait }; +//! use alexandria_data_structures::merkle_tree::{ Hasher, MerkleTree, poseidon::PoseidonHasherImpl, +//! MerkleTreeTrait }; //! //! // Create a new merkle tree instance. //! let mut merkle_tree: MerkleTree = MerkleTreeTrait::new(); @@ -104,18 +106,18 @@ pub impl MerkleTreeImpl, +Copy, +Drop> of MerkleTreeTra fn compute_root( ref self: MerkleTree, mut current_node: felt252, mut proof: Span ) -> felt252 { - while let Option::Some(proof_element) = proof - .pop_front() { - // Compute the hash of the current node and the current element of the proof. - // We need to check if the current node is smaller than the current element of the proof. - // If it is, we need to swap the order of the hash. - current_node = - if Into::::into(current_node) < (*proof_element).into() { - self.hasher.hash(current_node, *proof_element) - } else { - self.hasher.hash(*proof_element, current_node) - } - }; + for proof_element in proof { + // Compute the hash of the current node and the current element of the proof. + // We need to check if the current node is smaller than the current element of the + // proof. + // If it is, we need to swap the order of the hash. + current_node = + if Into::::into(current_node) < (*proof_element).into() { + self.hasher.hash(current_node, *proof_element) + } else { + self.hasher.hash(*proof_element, current_node) + } + }; current_node } @@ -129,18 +131,18 @@ pub impl MerkleTreeImpl, +Copy, +Drop> of MerkleTreeTra fn verify( ref self: MerkleTree, root: felt252, mut leaf: felt252, mut proof: Span ) -> bool { - while let Option::Some(proof_element) = proof - .pop_front() { - // Compute the hash of the current node and the current element of the proof. - // We need to check if the current node is smaller than the current element of the proof. - // If it is, we need to swap the order of the hash. - leaf = - if Into::::into(leaf) < (*proof_element).into() { - self.hasher.hash(leaf, *proof_element) - } else { - self.hasher.hash(*proof_element, leaf) - }; - }; + for proof_element in proof { + // Compute the hash of the current node and the current element of the proof. + // We need to check if the current node is smaller than the current element of the + // proof. + // If it is, we need to swap the order of the hash. + leaf = + if Into::::into(leaf) < (*proof_element).into() { + self.hasher.hash(leaf, *proof_element) + } else { + self.hasher.hash(*proof_element, leaf) + }; + }; leaf == root } @@ -202,15 +204,14 @@ fn get_next_level, +Drop>( mut nodes: Span, ref hasher: T ) -> Array { let mut next_level: Array = array![]; - while let Option::Some(left) = nodes - .pop_front() { - let right = *nodes.pop_front().expect('Index out of bounds'); - let node = if Into::::into(*left) < right.into() { - hasher.hash(*left, right) - } else { - hasher.hash(right, *left) - }; - next_level.append(node); + while let Option::Some(left) = nodes.pop_front() { + let right = *nodes.pop_front().expect('Index out of bounds'); + let node = if Into::::into(*left) < right.into() { + hasher.hash(*left, right) + } else { + hasher.hash(right, *left) }; + next_level.append(node); + }; next_level } diff --git a/packages/merkle_tree/src/storage_proof.cairo b/packages/merkle_tree/src/storage_proof.cairo index e0def38a..a4623168 100644 --- a/packages/merkle_tree/src/storage_proof.cairo +++ b/packages/merkle_tree/src/storage_proof.cairo @@ -72,9 +72,12 @@ pub impl ContractStateProofImpl of ContractStateProofTrait { } /// Verify Starknet storage proof. For reference see: -/// - ([state](https://docs.starknet.io/documentation/architecture_and_concepts/State/starknet-state/)) -/// - ([pathfinder_getproof API endpoint](https://github.com/eqlabs/pathfinder/blob/main/doc/rpc/pathfinder_rpc_api.json)) -/// - ([pathfinder storage implementation](https://github.com/eqlabs/pathfinder/blob/main/crates/merkle-tree/main/src/tree.rs)) +/// - +/// ([state](https://docs.starknet.io/documentation/architecture_and_concepts/State/starknet-state/)) +/// - ([pathfinder_getproof API +/// endpoint](https://github.com/eqlabs/pathfinder/blob/main/doc/rpc/pathfinder_rpc_api.json)) +/// - ([pathfinder storage +/// implementation](https://github.com/eqlabs/pathfinder/blob/main/crates/merkle-tree/main/src/tree.rs)) /// # Arguments /// * `expected_state_commitment` - state root `proof` is going to be verified against /// * `contract_address` - `contract_address` of the value to be verified diff --git a/packages/merkle_tree/src/tests/merkle_tree_test.cairo b/packages/merkle_tree/src/tests/merkle_tree_test.cairo index a3dfc791..464e0984 100644 --- a/packages/merkle_tree/src/tests/merkle_tree_test.cairo +++ b/packages/merkle_tree/src/tests/merkle_tree_test.cairo @@ -25,13 +25,13 @@ mod regular_call_merkle_tree_pedersen { // [Assert] Compute merkle root. let computed_root = merkle_tree.compute_root(leaf, valid_proof); - assert_eq!(computed_root, root, "compute valid root failed"); + assert_eq!(computed_root, root); // [Assert] Compute merkle proof. let mut input_leaves = leaves; let index = 0; let computed_proof = merkle_tree.compute_proof(input_leaves, index); - assert_eq!(computed_proof, valid_proof, "compute valid proof failed"); + assert_eq!(computed_proof, valid_proof); // [Assert] Verify a valid proof. let result = merkle_tree.verify(root, leaf, valid_proof); @@ -67,7 +67,7 @@ fn merkle_tree_pedersen_test() { let computed_root = MerkleTreeImpl::< _, PedersenHasherImpl >::compute_root(ref merkle_tree, leaf, valid_proof); - assert_eq!(computed_root, root, "compute valid root failed"); + assert_eq!(computed_root, root); // [Assert] Compute merkle proof. let mut input_leaves = leaves; @@ -75,7 +75,7 @@ fn merkle_tree_pedersen_test() { let computed_proof = MerkleTreeImpl::< _, PedersenHasherImpl >::compute_proof(ref merkle_tree, input_leaves, index); - assert_eq!(computed_proof, valid_proof, "compute valid proof failed"); + assert_eq!(computed_proof, valid_proof); // [Assert] Verify a valid proof. let result = MerkleTreeImpl::< @@ -116,7 +116,7 @@ fn merkle_tree_poseidon_test() { let computed_root = MerkleTreeImpl::< _, PoseidonHasherImpl >::compute_root(ref merkle_tree, leaf, valid_proof); - assert_eq!(computed_root, root, "compute valid root failed"); + assert_eq!(computed_root, root); // [Assert] Compute merkle proof. let mut input_leaves = leaves; @@ -124,7 +124,7 @@ fn merkle_tree_poseidon_test() { let computed_proof = MerkleTreeImpl::< _, PoseidonHasherImpl >::compute_proof(ref merkle_tree, input_leaves, index); - assert_eq!(computed_proof, valid_proof, "compute valid proof failed"); + assert_eq!(computed_proof, valid_proof); // [Assert] Verify a valid proof. let result = MerkleTreeImpl::< diff --git a/packages/merkle_tree/src/tests/storage_proof_test.cairo b/packages/merkle_tree/src/tests/storage_proof_test.cairo index fea8629d..3deee73f 100644 --- a/packages/merkle_tree/src/tests/storage_proof_test.cairo +++ b/packages/merkle_tree/src/tests/storage_proof_test.cairo @@ -16,7 +16,7 @@ fn balance_lsb_proof_test() { let expected_value = 8700000000000000005; let proof = balance_proof(); let value = verify(state_commitment, contract_address, storage_address, proof); - assert_eq!(expected_value, value, "wrong value"); + assert_eq!(expected_value, value); } #[test] @@ -29,7 +29,7 @@ fn balance_msb_proof_test() { let expected_value = 8700000000000000005; let proof = balance_proof(); let value = verify(state_commitment, contract_address, storage_address, proof); - assert_eq!(expected_value, value, "wrong value"); + assert_eq!(expected_value, value); } #[test] @@ -42,7 +42,7 @@ fn wrong_contract_address_proof_test() { let expected_value = 8700000000000000005; let proof = balance_proof(); let value = verify(state_commitment, contract_address, storage_address, proof); - assert_eq!(expected_value, value, "wrong value"); + assert_eq!(expected_value, value); } #[test] @@ -54,5 +54,5 @@ fn total_balance_lsb_proof_test() { let expected_value = 2970506847688829412026631; let proof = total_balance_proof(); let value = verify(state_commitment, contract_address, storage_address, proof); - assert_eq!(expected_value, value, "wrong value"); + assert_eq!(expected_value, value); } diff --git a/packages/merkle_tree/src/tests/storage_proof_test_data.cairo b/packages/merkle_tree/src/tests/storage_proof_test_data.cairo index cd0e572f..fefe6fea 100644 --- a/packages/merkle_tree/src/tests/storage_proof_test_data.cairo +++ b/packages/merkle_tree/src/tests/storage_proof_test_data.cairo @@ -5,7 +5,8 @@ use alexandria_merkle_tree::storage_proof::{ pub(crate) fn balance_proof() -> ContractStateProof { // func _balances(user : felt) -> (res : Uint256): - // get_storage_var_address('_balances', 0x063c94d6B73eA2284338f464f86F33E12642149F763Cd8E76E035E8E6A5Bb0e6) + // get_storage_var_address('_balances', + // 0x063c94d6B73eA2284338f464f86F33E12642149F763Cd8E76E035E8E6A5Bb0e6) // storage_address = 0x4ae51d08cd202d1472587dfe63dbf2d5ec767cbf4218b59b7ab71956780c6ee // ./get_storage_proof.sh 0x02f63993df97fb44439d8e2e999c8b9b51efba1eff78e5c994c709c82b442e65 \ // 0x00da114221cb83fa859dbdb4c44beeaa0bb37c7537ad5ae66fe5e0efd20e6eb3 \ diff --git a/packages/numeric/Scarb.toml b/packages/numeric/Scarb.toml index ad25b857..05d112fd 100644 --- a/packages/numeric/Scarb.toml +++ b/packages/numeric/Scarb.toml @@ -10,4 +10,7 @@ fmt.workspace = true [dependencies] alexandria_math = { path = "../math" } -alexandria_searching = { path = "../searching" } \ No newline at end of file +alexandria_searching = { path = "../searching" } + +[dev-dependencies] +cairo_test.workspace = true \ No newline at end of file diff --git a/packages/numeric/src/cumprod.cairo b/packages/numeric/src/cumprod.cairo index bde344ec..4b12c373 100644 --- a/packages/numeric/src/cumprod.cairo +++ b/packages/numeric/src/cumprod.cairo @@ -12,11 +12,10 @@ pub fn cumprod, +Copy, +Drop,>(mut sequence: Span) -> Array< // [Compute] Interpolation let mut prev_value = *sequence.pop_front().unwrap(); let mut array = array![prev_value]; - while let Option::Some(current_value) = sequence - .pop_front() { - let prod = *current_value * prev_value; - array.append(prod); - prev_value = prod; - }; + for current_value in sequence { + let prod = *current_value * prev_value; + array.append(prod); + prev_value = prod; + }; array } diff --git a/packages/numeric/src/cumsum.cairo b/packages/numeric/src/cumsum.cairo index c1a16be5..31732f4d 100644 --- a/packages/numeric/src/cumsum.cairo +++ b/packages/numeric/src/cumsum.cairo @@ -12,11 +12,10 @@ pub fn cumsum, +Copy, +Drop,>(mut sequence: Span) -> Array, +Sub, +Copy, +Drop, +Zero,>( // [Compute] Interpolation let mut prev_value = *sequence.pop_front().unwrap(); let mut array = array![Zero::zero()]; - while let Option::Some(current_value) = sequence - .pop_front() { - assert(*current_value >= prev_value, 'Sequence must be sorted'); - array.append(*current_value - prev_value); - prev_value = *current_value; - }; + for current_value in sequence { + assert(*current_value >= prev_value, 'Sequence must be sorted'); + array.append(*current_value - prev_value); + prev_value = *current_value; + }; array } diff --git a/packages/numeric/src/integers.cairo b/packages/numeric/src/integers.cairo index e88f2c6d..73b6b419 100644 --- a/packages/numeric/src/integers.cairo +++ b/packages/numeric/src/integers.cairo @@ -21,11 +21,10 @@ impl U32BytesImpl of UIntBytes { return Option::None; } let mut result: u32 = 0; - while let Option::Some(byte) = input - .pop_front() { - let byte: u32 = (*byte).into(); - result = result * 0x100 + byte; - }; + for byte in input { + let byte: u32 = (*byte).into(); + result = result * 0x100 + byte; + }; Option::Some(result) } diff --git a/packages/numeric/src/tests/cumprod_test.cairo b/packages/numeric/src/tests/cumprod_test.cairo index 387c6ce3..f41dc296 100644 --- a/packages/numeric/src/tests/cumprod_test.cairo +++ b/packages/numeric/src/tests/cumprod_test.cairo @@ -5,9 +5,9 @@ use alexandria_numeric::cumprod::cumprod; fn cumprod_test() { let xs: Array = array![3, 5, 7]; let ys = cumprod(xs.span()); - assert_eq!(*ys[0], *xs[0], "wrong value at index 0"); - assert_eq!(*ys[1], *xs[0] * *xs[1], "wrong value at index 1"); - assert_eq!(*ys[2], *xs[0] * *xs[1] * *xs[2], "wrong value at index 2"); + assert_eq!(*ys[0], *xs[0]); + assert_eq!(*ys[1], *xs[0] * *xs[1]); + assert_eq!(*ys[2], *xs[0] * *xs[1] * *xs[2]); } #[test] diff --git a/packages/numeric/src/tests/cumsum_test.cairo b/packages/numeric/src/tests/cumsum_test.cairo index 93f6717b..398d5835 100644 --- a/packages/numeric/src/tests/cumsum_test.cairo +++ b/packages/numeric/src/tests/cumsum_test.cairo @@ -5,9 +5,9 @@ use alexandria_numeric::cumsum::cumsum; fn cumsum_test() { let xs: Array = array![3, 5, 7]; let ys = cumsum(xs.span()); - assert_eq!(*ys[0], *xs[0], "wrong value at index 0"); - assert_eq!(*ys[1], *xs[0] + *xs[1], "wrong value at index 1"); - assert_eq!(*ys[2], *xs[0] + *xs[1] + *xs[2], "wrong value at index 2"); + assert_eq!(*ys[0], *xs[0]); + assert_eq!(*ys[1], *xs[0] + *xs[1]); + assert_eq!(*ys[2], *xs[0] + *xs[1] + *xs[2]); } #[test] diff --git a/packages/numeric/src/tests/diff_test.cairo b/packages/numeric/src/tests/diff_test.cairo index 5b0063e0..4623458d 100644 --- a/packages/numeric/src/tests/diff_test.cairo +++ b/packages/numeric/src/tests/diff_test.cairo @@ -5,9 +5,9 @@ use alexandria_numeric::diff::diff; fn diff_test() { let xs = array![3, 5, 7]; let ys = diff(xs.span()); - assert_eq!(*ys[0], 0_u256, "wrong value at index 0"); - assert_eq!(*ys[1], *xs[1] - *xs[0], "wrong value at index 1"); - assert_eq!(*ys[2], *xs[2] - *xs[1], "wrong value at index 2"); + assert_eq!(*ys[0], 0_u256); + assert_eq!(*ys[1], *xs[1] - *xs[0]); + assert_eq!(*ys[2], *xs[2] - *xs[1]); } #[test] diff --git a/packages/numeric/src/tests/integers_test.cairo b/packages/numeric/src/tests/integers_test.cairo index 0f0914ee..0e08e59e 100644 --- a/packages/numeric/src/tests/integers_test.cairo +++ b/packages/numeric/src/tests/integers_test.cairo @@ -7,7 +7,7 @@ fn test_u32_from_bytes() { let res: Option = UIntBytes::from_bytes(input.span()); assert!(res.is_some(), "should have a value"); - assert_eq!(res.unwrap(), 0xf4321562, "wrong result value"); + assert_eq!(res.unwrap(), 0xf4321562); } #[test] @@ -26,11 +26,11 @@ fn test_u32_to_bytes_full() { let input: u32 = 0xf4321562; let res: Span = input.to_bytes(); - assert_eq!(res.len(), 4, "wrong result length"); - assert_eq!(*res[0], 0xf4, "wrong result value"); - assert_eq!(*res[1], 0x32, "wrong result value"); - assert_eq!(*res[2], 0x15, "wrong result value"); - assert_eq!(*res[3], 0x62, "wrong result value"); + assert_eq!(res.len(), 4); + assert_eq!(*res[0], 0xf4); + assert_eq!(*res[1], 0x32); + assert_eq!(*res[2], 0x15); + assert_eq!(*res[3], 0x62); } #[test] @@ -39,10 +39,10 @@ fn test_u32_to_bytes_partial() { let input: u32 = 0xf43215; let res: Span = input.to_bytes(); - assert_eq!(res.len(), 3, "wrong result length"); - assert_eq!(*res[0], 0xf4, "wrong result value"); - assert_eq!(*res[1], 0x32, "wrong result value"); - assert_eq!(*res[2], 0x15, "wrong result value"); + assert_eq!(res.len(), 3); + assert_eq!(*res[0], 0xf4); + assert_eq!(*res[1], 0x32); + assert_eq!(*res[2], 0x15); } @@ -52,7 +52,7 @@ fn test_u32_to_bytes_leading_zeros() { let input: u32 = 0x00f432; let res: Span = input.to_bytes(); - assert_eq!(res.len(), 2, "wrong result length"); - assert_eq!(*res[0], 0xf4, "wrong result value"); - assert_eq!(*res[1], 0x32, "wrong result value"); + assert_eq!(res.len(), 2); + assert_eq!(*res[0], 0xf4); + assert_eq!(*res[1], 0x32); } diff --git a/packages/numeric/src/tests/trapezoidal_rule_test.cairo b/packages/numeric/src/tests/trapezoidal_rule_test.cairo index 2722a727..526a95de 100644 --- a/packages/numeric/src/tests/trapezoidal_rule_test.cairo +++ b/packages/numeric/src/tests/trapezoidal_rule_test.cairo @@ -5,7 +5,7 @@ use alexandria_numeric::trapezoidal_rule::trapezoidal_rule; fn trapezoidal_rule_test() { let xs: Array:: = array![3, 5, 7]; let ys = array![11, 13, 17]; - assert_eq!(trapezoidal_rule(xs.span(), ys.span()), 54, "invalid integral"); + assert_eq!(trapezoidal_rule(xs.span(), ys.span()), 54); } #[test] diff --git a/packages/numeric/src/trapezoidal_rule.cairo b/packages/numeric/src/trapezoidal_rule.cairo index 5856ff75..d703c9c7 100644 --- a/packages/numeric/src/trapezoidal_rule.cairo +++ b/packages/numeric/src/trapezoidal_rule.cairo @@ -1,6 +1,6 @@ use core::array::SpanTrait; use core::num::traits::Zero; -use core::option::OptionTrait; +use core::ops::AddAssign; //! Integrate using the composite trapezoidal rule /// Integrate y(x). @@ -13,7 +13,7 @@ pub fn trapezoidal_rule< T, +PartialOrd, +Add, - +AddEq, + +AddAssign, +Sub, +Mul, +Div, @@ -32,13 +32,12 @@ pub fn trapezoidal_rule< let mut prev_x = *xs.pop_front().unwrap(); let mut prev_y = *ys.pop_front().unwrap(); let mut value = Zero::zero(); - while let Option::Some(next_x) = xs - .pop_front() { - assert(*next_x > prev_x, 'Abscissa must be sorted'); - let next_y = *ys.pop_front().unwrap(); - value += (*next_x - prev_x) * (prev_y + next_y); - prev_x = *next_x; - prev_y = next_y; - }; + for next_x in xs { + assert(*next_x > prev_x, 'Abscissa must be sorted'); + let next_y = *ys.pop_front().unwrap(); + value += (*next_x - prev_x) * (prev_y + next_y); + prev_x = *next_x; + prev_y = next_y; + }; value / Into::into(2_u8) } diff --git a/packages/searching/Scarb.toml b/packages/searching/Scarb.toml index 79bceaae..1547ca76 100644 --- a/packages/searching/Scarb.toml +++ b/packages/searching/Scarb.toml @@ -11,3 +11,6 @@ fmt.workspace = true [dependencies] # dependency due to VecTrait usage in dijkstra.cairo alexandria_data_structures = { path = "../data_structures" } + +[dev-dependencies] +cairo_test.workspace = true \ No newline at end of file diff --git a/packages/searching/src/binary_search.cairo b/packages/searching/src/binary_search.cairo index 8c7cc785..10790bff 100644 --- a/packages/searching/src/binary_search.cairo +++ b/packages/searching/src/binary_search.cairo @@ -27,7 +27,7 @@ pub fn binary_search, +Drop, +PartialEq, +PartialOrd>( } } -pub fn binary_search_closest, impl TDrop: Drop, impl TOr: PartialOrd>( +pub fn binary_search_closest, +Drop, +PartialOrd>( span: Span, val: T ) -> Option { // Initial check diff --git a/packages/searching/src/bm_search.cairo b/packages/searching/src/bm_search.cairo index ac7b6555..1ec745cb 100644 --- a/packages/searching/src/bm_search.cairo +++ b/packages/searching/src/bm_search.cairo @@ -67,7 +67,8 @@ pub fn bm_search(text: @ByteArray, pattern: @ByteArray) -> Array { let current_char = text.at(shift + pattern_index - 1).unwrap(); let index = char_dict.get(current_char.into()); - // Calculate the next shift value based on the last occurrence of the current character in the pattern + // Calculate the next shift value based on the last occurrence of the current character + // in the pattern if pattern_index <= (index + 1) { shift += 1; } else { diff --git a/packages/searching/src/dijkstra.cairo b/packages/searching/src/dijkstra.cairo index 5604e413..74147dff 100644 --- a/packages/searching/src/dijkstra.cairo +++ b/packages/searching/src/dijkstra.cairo @@ -68,10 +68,9 @@ impl GraphImpl of GraphTrait { // iterate over existing array to add new node if !is_null { - while let Option::Some(current_value) = span - .pop_front() { - nodes.append(*current_value); - }; + for current_value in span { + nodes.append(*current_value); + }; nodes.append(node); } // add node diff --git a/packages/searching/src/tests/binary_search_closest_test.cairo b/packages/searching/src/tests/binary_search_closest_test.cairo index a44e78c8..e14dd829 100644 --- a/packages/searching/src/tests/binary_search_closest_test.cairo +++ b/packages/searching/src/tests/binary_search_closest_test.cairo @@ -34,16 +34,16 @@ fn value_not_found() { // Test with an even length let mut span = arr.span(); - assert!(search(span, 20).is_none(), "value was found"); - assert!(search(span, 42000).is_none(), "value was found"); - assert!(search(span, 760).is_none(), "value was found"); + assert!(search(span, 20).is_none()); + assert!(search(span, 42000).is_none()); + assert!(search(span, 760).is_none()); // Odd length arr.append(700); span = arr.span(); - assert!(search(span, 20).is_none(), "value was found"); - assert!(search(span, 42000).is_none(), "value was found"); - assert!(search(span, 760).is_none(), "value was found"); + assert!(search(span, 20).is_none()); + assert!(search(span, 42000).is_none()); + assert!(search(span, 760).is_none()); } #[test] @@ -74,24 +74,24 @@ fn zero_length_span() { #[available_gas(1_000_000)] fn length_two_span() { let span: Span = array![100, 200].span(); - assert!(search(span, 50).is_none(), "value was found"); + assert!(search(span, 50).is_none()); assert_eq!(search(span, 100).unwrap(), 0); assert_eq!(search(span, 150).unwrap(), 0); assert_eq!(search(span, 200).unwrap(), 1); - assert!(search(span, 250).is_none(), "value was found"); + assert!(search(span, 250).is_none()); } #[test] #[available_gas(1_000_000)] fn length_three_span() { let span: Span = array![100, 200, 300].span(); - assert!(search(span, 50).is_none(), "value was found"); + assert!(search(span, 50).is_none()); assert_eq!(search(span, 100).unwrap(), 0); assert_eq!(search(span, 150).unwrap(), 0); assert_eq!(search(span, 200).unwrap(), 1); assert_eq!(search(span, 250).unwrap(), 1); assert_eq!(search(span, 300).unwrap(), 2); - assert!(search(span, 350).is_none(), "value was found"); + assert!(search(span, 350).is_none()); } #[test] @@ -127,7 +127,7 @@ fn all_values() { let mut span = arr.span(); // Test with an even length - assert!(search(span, 50).is_none(), "value was found"); + assert!(search(span, 50).is_none()); assert_eq!(search(span, 100).unwrap(), 0); assert_eq!(search(span, 150).unwrap(), 0); assert_eq!(search(span, 200).unwrap(), 1); @@ -139,12 +139,12 @@ fn all_values() { assert_eq!(search(span, 500).unwrap(), 4); assert_eq!(search(span, 550).unwrap(), 4); assert_eq!(search(span, 600).unwrap(), 5); - assert!(search(span, 650).is_none(), "value was found"); + assert!(search(span, 650).is_none()); // Odd length arr.append(700); span = arr.span(); - assert!(search(span, 50).is_none(), "value was found"); + assert!(search(span, 50).is_none()); assert_eq!(search(span, 100).unwrap(), 0); assert_eq!(search(span, 150).unwrap(), 0); assert_eq!(search(span, 200).unwrap(), 1); @@ -158,5 +158,5 @@ fn all_values() { assert_eq!(search(span, 600).unwrap(), 5); assert_eq!(search(span, 650).unwrap(), 5); assert_eq!(search(span, 700).unwrap(), 6); - assert!(search(span, 750).is_none(), "value was found"); + assert!(search(span, 750).is_none()); } diff --git a/packages/searching/src/tests/binary_search_test.cairo b/packages/searching/src/tests/binary_search_test.cairo index 87754005..693649ab 100644 --- a/packages/searching/src/tests/binary_search_test.cairo +++ b/packages/searching/src/tests/binary_search_test.cairo @@ -8,23 +8,23 @@ fn value_found() { let mut span = arr.span(); // Test with an even length - assert_eq!(binary_search(span, 100).unwrap(), 0, "Should be index 0"); - assert_eq!(binary_search(span, 200).unwrap(), 1, "Should be index 1"); - assert_eq!(binary_search(span, 300).unwrap(), 2, "Should be index 2"); - assert_eq!(binary_search(span, 400).unwrap(), 3, "Should be index 3"); - assert_eq!(binary_search(span, 500).unwrap(), 4, "Should be index 4"); - assert_eq!(binary_search(span, 600).unwrap(), 5, "Should be index 5"); + assert_eq!(binary_search(span, 100).unwrap(), 0); + assert_eq!(binary_search(span, 200).unwrap(), 1); + assert_eq!(binary_search(span, 300).unwrap(), 2); + assert_eq!(binary_search(span, 400).unwrap(), 3); + assert_eq!(binary_search(span, 500).unwrap(), 4); + assert_eq!(binary_search(span, 600).unwrap(), 5); // Odd length arr.append(700); span = arr.span(); - assert_eq!(binary_search(span, 100).unwrap(), 0, "Should be index 0"); - assert_eq!(binary_search(span, 200).unwrap(), 1, "Should be index 1"); - assert_eq!(binary_search(span, 300).unwrap(), 2, "Should be index 2"); - assert_eq!(binary_search(span, 400).unwrap(), 3, "Should be index 3"); - assert_eq!(binary_search(span, 500).unwrap(), 4, "Should be index 4"); - assert_eq!(binary_search(span, 600).unwrap(), 5, "Should be index 5"); - assert_eq!(binary_search(span, 700).unwrap(), 6, "Should be index 6"); + assert_eq!(binary_search(span, 100).unwrap(), 0); + assert_eq!(binary_search(span, 200).unwrap(), 1); + assert_eq!(binary_search(span, 300).unwrap(), 2); + assert_eq!(binary_search(span, 400).unwrap(), 3); + assert_eq!(binary_search(span, 500).unwrap(), 4); + assert_eq!(binary_search(span, 600).unwrap(), 5); + assert_eq!(binary_search(span, 700).unwrap(), 6); } #[test] @@ -34,16 +34,16 @@ fn value_not_found() { // Test with an even length let mut span = arr.span(); - assert!(binary_search(span, 20).is_none(), "value was found"); - assert!(binary_search(span, 42000).is_none(), "value was found"); - assert!(binary_search(span, 760).is_none(), "value was found"); + assert!(binary_search(span, 20).is_none()); + assert!(binary_search(span, 42000).is_none()); + assert!(binary_search(span, 760).is_none()); // Odd length arr.append(700); // 6 span = arr.span(); - assert!(binary_search(span, 20).is_none(), "value was found"); - assert!(binary_search(span, 42000).is_none(), "value was found"); - assert!(binary_search(span, 760).is_none(), "value was found"); + assert!(binary_search(span, 20).is_none()); + assert!(binary_search(span, 42000).is_none()); + assert!(binary_search(span, 760).is_none()); } #[test] diff --git a/packages/searching/src/tests/bm_search_test.cairo b/packages/searching/src/tests/bm_search_test.cairo index 37b2d38c..ee4842a1 100644 --- a/packages/searching/src/tests/bm_search_test.cairo +++ b/packages/searching/src/tests/bm_search_test.cairo @@ -3,7 +3,8 @@ use alexandria_searching::bm_search::bm_search; #[test] #[available_gas(5000000)] fn bm_search_test_1() { - // AABCAB12AFAABCABFFEGABCAB -> 41,41,42,43,41,42,31,32,41,46,41,41,42,43,41,42,46,46,45,47,41,42,43,41,42 + // AABCAB12AFAABCABFFEGABCAB -> + // 41,41,42,43,41,42,31,32,41,46,41,41,42,43,41,42,46,46,45,47,41,42,43,41,42 let mut text: ByteArray = Default::default(); text.append_byte(0x41_u8); text.append_byte(0x41_u8); @@ -40,13 +41,14 @@ fn bm_search_test_1() { let positions = bm_search(@text, @pattern); let ground_truth: Array = array![1, 11, 20]; - assert_eq!(positions.span(), ground_truth.span(), "invalid result"); + assert_eq!(positions.span(), ground_truth.span()); } #[test] #[available_gas(5000000)] fn bm_search_test_2() { - // AABCAB12AFAABCABFFEGABCAB -> 41,41,42,43,41,42,31,32,41,46,41,41,42,43,41,42,46,46,45,47,41,42,43,41,42 + // AABCAB12AFAABCABFFEGABCAB -> + // 41,41,42,43,41,42,31,32,41,46,41,41,42,43,41,42,46,46,45,47,41,42,43,41,42 let mut text: ByteArray = Default::default(); text.append_byte(0x41_u8); text.append_byte(0x41_u8); @@ -81,13 +83,14 @@ fn bm_search_test_2() { let positions = bm_search(@text, @pattern); let ground_truth: Array = array![]; - assert_eq!(positions.span(), ground_truth.span(), "invalid result"); + assert_eq!(positions.span(), ground_truth.span()); } #[test] #[available_gas(5000000)] fn bm_search_test_3() { - // AABCAB12AFAABCABFFEGABCAB -> 41,41,42,43,41,42,31,32,41,46,41,41,42,43,41,42,46,46,45,47,41,42,43,41,42 + // AABCAB12AFAABCABFFEGABCAB -> + // 41,41,42,43,41,42,31,32,41,46,41,41,42,43,41,42,46,46,45,47,41,42,43,41,42 let mut text: ByteArray = Default::default(); text.append_byte(0x41_u8); text.append_byte(0x41_u8); @@ -122,5 +125,5 @@ fn bm_search_test_3() { let positions = bm_search(@text, @pattern); let ground_truth: Array = array![3, 13, 22]; - assert_eq!(positions.span(), ground_truth.span(), "invalid result"); + assert_eq!(positions.span(), ground_truth.span()); } diff --git a/packages/searching/src/tests/dijkstra_test.cairo b/packages/searching/src/tests/dijkstra_test.cairo index 3c62d0ce..05e90717 100644 --- a/packages/searching/src/tests/dijkstra_test.cairo +++ b/packages/searching/src/tests/dijkstra_test.cairo @@ -16,7 +16,7 @@ fn add_edge() { GraphTrait::add_edge(ref graph, 2, 1, 2); GraphTrait::add_edge(ref graph, 2, 3, 3); - assert_eq!(graph.nodes.len(), 6, "wrong node number"); + assert_eq!(graph.nodes.len(), 6); let val = graph.adj_nodes(source.into()); let span = match match_nullable(val) { @@ -24,15 +24,15 @@ fn add_edge() { FromNullableResult::NotNull(val) => { val.unbox() }, }; - assert_eq!(span.len(), 4, "wrong nb of adj edge for node 0"); + assert_eq!(span.len(), 4); let new_node = *span.get(1).unwrap().unbox(); - assert_eq!(*new_node.dest(), dest + 1, "Wrong dest in adj edge"); - assert_eq!(*new_node.weight(), weight + 1, "Wrong weight in adj edge"); + assert_eq!(*new_node.dest(), dest + 1); + assert_eq!(*new_node.weight(), weight + 1); let new_node = *span.get(3).unwrap().unbox(); - assert_eq!(*new_node.dest(), dest + 3, "Wrong dest in adj edge"); - assert_eq!(*new_node.weight(), weight + 3, "Wrong weight in adj edge"); + assert_eq!(*new_node.dest(), dest + 3); + assert_eq!(*new_node.weight(), weight + 3); let val = graph.adj_nodes(2.into()); @@ -41,7 +41,7 @@ fn add_edge() { FromNullableResult::NotNull(val) => { val.unbox() }, }; - assert_eq!(span.len(), 2, "wrong nb of adj edge for node 2"); + assert_eq!(span.len(), 2); } @@ -59,12 +59,12 @@ fn calculate_shortest_path() { let mut results: Felt252Dict = GraphTrait::shortest_path(ref graph, 0_u32); - assert_eq!(results.get(0.into()), 0, "Wrong weight for node 0"); - assert_eq!(results.get(1.into()), 5, "Wrong weight for node 1"); - assert_eq!(results.get(2.into()), 3, "Wrong weight for node 2"); - assert_eq!(results.get(3.into()), 2, "Wrong weight for node 3"); - assert_eq!(results.get(4.into()), 3, "Wrong weight for node 4"); - assert_eq!(results.get(5.into()), 3, "Wrong weight for node 5"); + assert_eq!(results.get(0.into()), 0); + assert_eq!(results.get(1.into()), 5); + assert_eq!(results.get(2.into()), 3); + assert_eq!(results.get(3.into()), 2); + assert_eq!(results.get(4.into()), 3); + assert_eq!(results.get(5.into()), 3); } #[test] @@ -80,11 +80,11 @@ fn calculate_shortest_path_random() { let mut results: Felt252Dict = GraphTrait::shortest_path(ref graph, 0_u32); - assert_eq!(results.get(0.into()), 0, "Wrong weight for node 0"); - assert_eq!(results.get(2.into()), 4, "Wrong weight for node 2"); - assert_eq!(results.get(3.into()), 5, "Wrong weight for node 3"); - assert_eq!(results.get(1.into()), 8, "Wrong weight for node 1"); - assert_eq!(results.get(4.into()), 7, "Wrong weight for node 4"); + assert_eq!(results.get(0.into()), 0); + assert_eq!(results.get(2.into()), 4); + assert_eq!(results.get(3.into()), 5); + assert_eq!(results.get(1.into()), 8); + assert_eq!(results.get(4.into()), 7); } @@ -101,11 +101,11 @@ fn calculate_shortest_path_node_visited() { let mut results: Felt252Dict = GraphTrait::shortest_path(ref graph, 0_u32); - assert_eq!(results.get(0.into()), 0, "Wrong weight for node 0"); - assert_eq!(results.get(1.into()), 5, "Wrong weight for node 1"); - assert_eq!(results.get(2.into()), 3, "Wrong weight for node 2"); - assert_eq!(results.get(3.into()), 2, "Wrong weight for node 3"); - assert_eq!(results.get(4.into()), 3, "Wrong weight for node 4"); - assert_eq!(results.get(5.into()), 3, "Wrong weight for node 5"); + assert_eq!(results.get(0.into()), 0); + assert_eq!(results.get(1.into()), 5); + assert_eq!(results.get(2.into()), 3); + assert_eq!(results.get(3.into()), 2); + assert_eq!(results.get(4.into()), 3); + assert_eq!(results.get(5.into()), 3); } diff --git a/packages/searching/src/tests/levenshtein_distance_test.cairo b/packages/searching/src/tests/levenshtein_distance_test.cairo index 9a40b8bc..6bed89c3 100644 --- a/packages/searching/src/tests/levenshtein_distance_test.cairo +++ b/packages/searching/src/tests/levenshtein_distance_test.cairo @@ -17,7 +17,7 @@ fn bm_search_test_1() { arr2.append_byte(0x47_u8); let dist = levenshtein_distance(@arr1, @arr2); - assert_eq!(dist, 2, "invalid result"); + assert_eq!(dist, 2); } #[test] @@ -27,7 +27,7 @@ fn bm_search_test_2() { let mut arr2: ByteArray = Default::default(); let dist = levenshtein_distance(@arr1, @arr2); - assert_eq!(dist, 0, "invalid result"); + assert_eq!(dist, 0); } #[test] @@ -38,7 +38,7 @@ fn bm_search_test_3() { arr2.append_byte(0x61_u8); let dist = levenshtein_distance(@arr1, @arr2); - assert_eq!(dist, 1, "invalid result"); + assert_eq!(dist, 1); } #[test] @@ -49,7 +49,7 @@ fn bm_search_test_4() { let mut arr2: ByteArray = Default::default(); let dist = levenshtein_distance(@arr1, @arr2); - assert_eq!(dist, 1, "invalid result"); + assert_eq!(dist, 1); } #[test] @@ -62,7 +62,7 @@ fn bm_search_test_5() { arr2.append_byte(0x61_u8); let dist = levenshtein_distance(@arr1, @arr2); - assert_eq!(dist, 1, "invalid result"); + assert_eq!(dist, 1); } #[test] @@ -86,7 +86,7 @@ fn bm_search_test_6() { arr2.append_byte(0x72_u8); let dist = levenshtein_distance(@arr1, @arr2); - assert_eq!(dist, 0, "invalid result"); + assert_eq!(dist, 0); } #[test] @@ -110,5 +110,5 @@ fn bm_search_test_7() { arr2.append_byte(0x6f_u8); let dist = levenshtein_distance(@arr1, @arr2); - assert_eq!(dist, 6, "invalid result"); + assert_eq!(dist, 6); } diff --git a/packages/sorting/Scarb.toml b/packages/sorting/Scarb.toml index c5341ac4..273b3ea9 100644 --- a/packages/sorting/Scarb.toml +++ b/packages/sorting/Scarb.toml @@ -10,3 +10,6 @@ fmt.workspace = true [dependencies] alexandria_data_structures = { path = "../data_structures" } + +[dev-dependencies] +cairo_test.workspace = true \ No newline at end of file diff --git a/packages/sorting/src/merge_sort.cairo b/packages/sorting/src/merge_sort.cairo index 59c61124..b0f20678 100644 --- a/packages/sorting/src/merge_sort.cairo +++ b/packages/sorting/src/merge_sort.cairo @@ -24,8 +24,8 @@ pub impl MergeSort of Sortable { let right_arr = array.slice(middle, len - middle); // Recursively sort the left and right arrays - let sorted_left = MergeSort::sort(left_arr); - let sorted_right = MergeSort::sort(right_arr); + let sorted_left = Self::sort(left_arr); + let sorted_right = Self::sort(right_arr); let mut result_arr = array![]; merge_recursive(sorted_left, sorted_right, ref result_arr, 0, 0); diff --git a/packages/sorting/src/tests/bubble_sort_test.cairo b/packages/sorting/src/tests/bubble_sort_test.cairo index 14ce6c27..88798b90 100644 --- a/packages/sorting/src/tests/bubble_sort_test.cairo +++ b/packages/sorting/src/tests/bubble_sort_test.cairo @@ -8,7 +8,7 @@ fn bubble_sort_test() { let sorted = BubbleSort::sort(data); - assert_eq!(sorted.span(), correct.span(), "invalid result"); + assert_eq!(sorted.span(), correct.span()); } @@ -20,7 +20,7 @@ fn bubble_sort_test_empty() { let sorted = BubbleSort::sort(data); - assert_eq!(sorted.span(), correct.span(), "invalid result"); + assert_eq!(sorted.span(), correct.span()); } #[test] @@ -31,7 +31,7 @@ fn bubble_sort_test_one_element() { let sorted = BubbleSort::sort(data); - assert_eq!(sorted.span(), correct.span(), "invalid result"); + assert_eq!(sorted.span(), correct.span()); } #[test] @@ -42,7 +42,7 @@ fn bubble_sort_test_pre_sorted() { let sorted = BubbleSort::sort(data); - assert_eq!(sorted.span(), correct.span(), "invalid result"); + assert_eq!(sorted.span(), correct.span()); } #[test] @@ -53,7 +53,7 @@ fn bubble_sort_test_pre_sorted_decreasing() { let sorted = BubbleSort::sort(data); - assert_eq!(sorted.span(), correct.span(), "invalid result"); + assert_eq!(sorted.span(), correct.span()); } #[test] @@ -64,7 +64,7 @@ fn bubble_sort_test_pre_sorted_2_same_values() { let sorted = BubbleSort::sort(data); - assert_eq!(sorted.span(), correct.span(), "invalid result"); + assert_eq!(sorted.span(), correct.span()); } #[test] @@ -75,5 +75,5 @@ fn bubble_sort_test_2_same_values() { let sorted = BubbleSort::sort(data); - assert_eq!(sorted.span(), correct.span(), "invalid result"); + assert_eq!(sorted.span(), correct.span()); } diff --git a/packages/sorting/src/tests/merge_sort_test.cairo b/packages/sorting/src/tests/merge_sort_test.cairo index 250eae95..f8fcb242 100644 --- a/packages/sorting/src/tests/merge_sort_test.cairo +++ b/packages/sorting/src/tests/merge_sort_test.cairo @@ -8,7 +8,7 @@ fn merge_sort_test() { let sorted = MergeSort::sort(data); - assert_eq!(sorted, correct, "invalid result"); + assert_eq!(sorted, correct); } #[test] @@ -19,7 +19,7 @@ fn merge_sort_test_2_pre_sorted_decreasing() { let sorted = MergeSort::sort(data); - assert_eq!(sorted, correct, "invalid result"); + assert_eq!(sorted, correct); } #[test] @@ -31,7 +31,7 @@ fn merge_sort_test_empty() { let sorted = MergeSort::sort(data); - assert_eq!(sorted, correct, "invalid result"); + assert_eq!(sorted, correct); } #[test] @@ -42,7 +42,7 @@ fn merge_sort_test_one_element() { let sorted = MergeSort::sort(data); - assert_eq!(sorted, correct, "invalid result"); + assert_eq!(sorted, correct); } #[test] @@ -53,7 +53,7 @@ fn merge_sort_test_pre_sorted() { let sorted = MergeSort::sort(data); - assert_eq!(sorted, correct, "invalid result"); + assert_eq!(sorted, correct); } #[test] @@ -64,7 +64,7 @@ fn merge_sort_test_2_same_values() { let sorted = MergeSort::sort(data); - assert_eq!(sorted, correct, "invalid result"); + assert_eq!(sorted, correct); } #[test] @@ -75,5 +75,5 @@ fn merge_sort_test_2_same_values_pre_sorted() { let sorted = MergeSort::sort(data); - assert_eq!(sorted, correct, "invalid result"); + assert_eq!(sorted, correct); } diff --git a/packages/sorting/src/tests/quick_sort_test.cairo b/packages/sorting/src/tests/quick_sort_test.cairo index a086e54d..d6ddb6ad 100644 --- a/packages/sorting/src/tests/quick_sort_test.cairo +++ b/packages/sorting/src/tests/quick_sort_test.cairo @@ -39,7 +39,7 @@ fn quicksort_test() { let sorted = QuickSort::sort(data); - assert!(is_equal_vec(sorted, correct.span()), "invalid result"); + assert!(is_equal_vec(sorted, correct.span())); } @@ -51,7 +51,7 @@ fn quicksort_test_empty() { let sorted = QuickSort::sort(data); - assert!(is_equal_vec(sorted, correct.span()), "invalid result"); + assert!(is_equal_vec(sorted, correct.span())); } #[test] @@ -63,7 +63,7 @@ fn quicksort_test_one_element() { let sorted = QuickSort::sort(data); - assert!(is_equal_vec(sorted, correct.span()), "invalid result"); + assert!(is_equal_vec(sorted, correct.span())); } #[test] @@ -78,7 +78,7 @@ fn quicksort_test_pre_sorted() { let sorted = QuickSort::sort(data); - assert!(is_equal_vec(sorted, correct.span()), "invalid result"); + assert!(is_equal_vec(sorted, correct.span())); } #[test] @@ -93,7 +93,7 @@ fn quicksort_test_pre_sorted_decreasing() { let sorted = QuickSort::sort(data); - assert!(is_equal_vec(sorted, correct.span()), "invalid result"); + assert!(is_equal_vec(sorted, correct.span())); } #[test] @@ -108,7 +108,7 @@ fn quicksort_test_pre_sorted_2_same_values() { let sorted = QuickSort::sort(data); - assert!(is_equal_vec(sorted, correct.span()), "invalid result"); + assert!(is_equal_vec(sorted, correct.span())); } #[test] @@ -123,5 +123,5 @@ fn quicksort_test_2_same_values() { let sorted = QuickSort::sort(data); - assert!(is_equal_vec(sorted, correct.span()), "invalid result"); + assert!(is_equal_vec(sorted, correct.span())); } diff --git a/packages/storage/Scarb.toml b/packages/storage/Scarb.toml index 052aad35..1b1bdb36 100644 --- a/packages/storage/Scarb.toml +++ b/packages/storage/Scarb.toml @@ -10,3 +10,6 @@ fmt.workspace = true [dependencies] starknet.workspace = true + +[dev-dependencies] +cairo_test.workspace = true \ No newline at end of file diff --git a/packages/storage/src/list.cairo b/packages/storage/src/list.cairo index ffa074f0..d4d29985 100644 --- a/packages/storage/src/list.cairo +++ b/packages/storage/src/list.cairo @@ -1,3 +1,4 @@ +use core::ops::index::IndexView; use core::poseidon::poseidon_hash_span; use core::traits::DivRem; use starknet::storage_access::{ @@ -14,6 +15,9 @@ pub struct List { len: u32, // number of elements in array } +#[deprecated( + feature: "deprecated-list-trait", note: "Use `starknet::storage::Vec`.", since: "2.7.0" +)] pub trait ListTrait { /// Instantiates a new List with the given base address. /// @@ -272,22 +276,27 @@ impl ListImpl, +Drop, +Store> of ListTrait { } } -impl AListIndexViewImpl, +Drop, +Store> of IndexView, u32, T> { +impl AListIndexViewImpl, +Drop, +Store> of IndexView, u32> { + type Target = T; + fn index(self: @List, index: u32) -> T { self.get(index).expect('read syscall failed').expect('List index out of bounds') } } -// this functions finds the StorageBaseAddress of a "storage segment" (a continuous space of 256 storage slots) +// this functions finds the StorageBaseAddress of a "storage segment" (a continuous space of 256 +// storage slots) // and an offset into that segment where a value at `index` is stored // each segment can hold up to `256 // storage_size` elements // // the way how the address is calculated is very similar to how a LegacyHash map works: // // first we take the `list_base` address which is derived from the name of the storage variable -// then we hash it with a `key` which is the number of the segment where the element at `index` belongs (from 0 upwards) +// then we hash it with a `key` which is the number of the segment where the element at `index` +// belongs (from 0 upwards) // we hash these two values: H(list_base, key) to the the `segment_base` address -// finally, we calculate the offset into this segment, taking into account the size of the elements held in the array +// finally, we calculate the offset into this segment, taking into account the size of the elements +// held in the array // // by way of example: // diff --git a/packages/storage/src/tests.cairo b/packages/storage/src/tests.cairo index b19301c3..31ab8b1e 100644 --- a/packages/storage/src/tests.cairo +++ b/packages/storage/src/tests.cairo @@ -1 +1,3 @@ +#[cfg(test)] mod list_test; + diff --git a/packages/storage/src/tests/list_test.cairo b/packages/storage/src/tests/list_test.cairo index 8cb1ebeb..a0ea8ea7 100644 --- a/packages/storage/src/tests/list_test.cairo +++ b/packages/storage/src/tests/list_test.cairo @@ -1,4 +1,14 @@ -use starknet::ContractAddress; +use alexandria_storage::{List, ListTrait}; +use core::option::OptionTrait; +use core::starknet::storage::StorageAsPointer; +use core::traits::TryInto; +use starknet::{ + ClassHash, ContractAddress, syscalls::deploy_syscall, SyscallResultTrait, + testing::set_contract_address, + storage_access::{ + storage_base_address_from_felt252, storage_address_from_base, StorageBaseAddress + } +}; #[starknet::interface] trait IAListHolder { @@ -108,457 +118,434 @@ mod AListHolder { } } -#[cfg(test)] -mod tests { - use AListHolder::{addressesContractMemberStateTrait, numbersContractMemberStateTrait}; - use alexandria_storage::{List, ListTrait}; - use starknet::{ - ClassHash, ContractAddress, syscalls::deploy_syscall, SyscallResultTrait, - testing::set_contract_address, - storage_access::{ - storage_base_address_from_felt252, storage_address_from_base, StorageBaseAddress - } - }; - use super::{AListHolder, IAListHolderDispatcher, IAListHolderDispatcherTrait}; - - impl StorageBaseAddressPartialEq of PartialEq { - fn eq(lhs: @StorageBaseAddress, rhs: @StorageBaseAddress) -> bool { - let left: felt252 = storage_address_from_base(*lhs).into(); - left == storage_address_from_base(*rhs).into() - } - - fn ne(lhs: @StorageBaseAddress, rhs: @StorageBaseAddress) -> bool { - !StorageBaseAddressPartialEq::eq(lhs, rhs) - } +impl StorageBaseAddressPartialEq of PartialEq { + fn eq(lhs: @StorageBaseAddress, rhs: @StorageBaseAddress) -> bool { + let left: felt252 = storage_address_from_base(*lhs).into(); + left == storage_address_from_base(*rhs).into() } - fn deploy_mock() -> IAListHolderDispatcher { - let class_hash: ClassHash = AListHolder::TEST_CLASS_HASH.try_into().unwrap(); - let ctor_data: Array = Default::default(); - let (addr, _) = deploy_syscall(class_hash, 0, ctor_data.span(), false).unwrap_syscall(); - IAListHolderDispatcher { contract_address: addr } + fn ne(lhs: @StorageBaseAddress, rhs: @StorageBaseAddress) -> bool { + !Self::eq(lhs, rhs) } +} - fn mock_addr() -> ContractAddress { - starknet::contract_address_const::<'hello'>() - } +fn deploy_mock() -> IAListHolderDispatcher { + let class_hash: ClassHash = AListHolder::TEST_CLASS_HASH.try_into().unwrap(); + let ctor_data: Array = Default::default(); + let (addr, _) = deploy_syscall(class_hash, 0, ctor_data.span(), false).unwrap_syscall(); + IAListHolderDispatcher { contract_address: addr } +} - #[test] - #[available_gas(100000000)] - fn test_deploy() { - let contract = deploy_mock(); - assert_eq!(contract.do_get_len(), (0, 0), "do_get_len"); - } +fn mock_addr() -> ContractAddress { + starknet::contract_address_const::<'hello'>() +} - #[test] - #[available_gas(100000000)] - fn test_new_initializes_empty_list() { - let contract = deploy_mock(); - set_contract_address(contract.contract_address); - let contract_state = AListHolder::unsafe_new_contract_state(); - - let addresses_address = contract_state.addresses.address(); - let addresses_list = ListTrait::::new(0, addresses_address); - assert_eq!(addresses_list.address_domain, 0, "Address domain should be 0"); - assert_eq!(addresses_list.len(), 0, "Initial length should be 0"); - assert_eq!(addresses_list.base.into(), addresses_address, "Base address mismatch"); - assert_eq!(addresses_list.storage_size(), 1, "Storage size should be 1"); - - let numbers_address = contract_state.numbers.address(); - let numbers_list = ListTrait::::new(0, numbers_address); - assert_eq!(numbers_list.address_domain, 0, "Address domain should be 0"); - assert_eq!(numbers_list.len(), 0, "Initial length should be 0"); - assert_eq!(numbers_list.base.into(), numbers_address, "Base address mismatch"); - assert_eq!(numbers_list.storage_size(), 2, "Storage size should be 2"); - - // Check if both addresses and numbers lists are initialized to be empty - assert_eq!(contract.do_get_len(), (0, 0), "Initial lengths should be 0"); - assert_eq!(contract.do_is_empty(), (true, true), "Lists should be empty"); - } +#[test] +#[available_gas(100000000)] +fn test_deploy() { + let contract = deploy_mock(); + assert_eq!(contract.do_get_len(), (0, 0)); +} - #[test] - #[available_gas(100000000)] - fn test_new_then_fill_list() { - let contract = deploy_mock(); - set_contract_address(contract.contract_address); - let contract_state = AListHolder::unsafe_new_contract_state(); +#[test] +#[available_gas(100000000)] +fn test_new_initializes_empty_list() { + let mut contract_state = AListHolder::contract_state_for_testing(); + + let addresses_address = contract_state.addresses.as_ptr().__storage_pointer_address__; + let addresses_list = ListTrait::::new(0, addresses_address); + assert_eq!(addresses_list.address_domain, 0); + assert_eq!(addresses_list.len(), 0); + assert_eq!(addresses_list.base.into(), addresses_address); + assert_eq!(addresses_list.storage_size(), 1); + + let numbers_address = contract_state.numbers.as_ptr().__storage_pointer_address__; + let numbers_list = ListTrait::::new(0, numbers_address); + assert_eq!(numbers_list.address_domain, 0); + assert_eq!(numbers_list.len(), 0); + assert_eq!(numbers_list.base.into(), numbers_address); + assert_eq!(numbers_list.storage_size(), 2); + + // Check if both addresses and numbers lists are initialized to be empty + assert_eq!(contract_state.do_get_len(), (0, 0)); + assert_eq!(contract_state.do_is_empty(), (true, true)); +} - let addresses_address = contract_state.addresses.address(); - let mut addresses_list = ListTrait::::new(0, addresses_address); +#[test] +#[available_gas(100000000)] +fn test_new_then_fill_list() { + let mut contract_state = AListHolder::contract_state_for_testing(); - let numbers_address = contract_state.numbers.address(); - let mut numbers_list = ListTrait::::new(0, numbers_address); + let addresses_address = contract_state.addresses.as_ptr().__storage_pointer_address__; + let mut addresses_list = ListTrait::::new(0, addresses_address); - let _ = addresses_list.append(mock_addr()); - let _ = numbers_list.append(1); - let _ = numbers_list.append(2); + let numbers_address = contract_state.numbers.as_ptr().__storage_pointer_address__; + let mut numbers_list = ListTrait::::new(0, numbers_address); - assert_eq!(addresses_list.len(), 1, "Addresses length should be 1"); - assert_eq!(numbers_list.len(), 2, "Numbers length should be 2"); + let _ = addresses_list.append(mock_addr()); + let _ = numbers_list.append(1); + let _ = numbers_list.append(2); - assert_eq!(contract.do_get_len(), (1, 2), "Lengths should be (1,2)"); - assert_eq!(contract.do_is_empty(), (false, false), "Lists should not be empty"); - } + assert_eq!(addresses_list.len(), 1); + assert_eq!(numbers_list.len(), 2); - #[test] - #[available_gas(100000000)] - fn test_fetch_empty_list() { - let contract = deploy_mock(); - set_contract_address(contract.contract_address); - let storage_address = storage_base_address_from_felt252('empty_address'); + assert_eq!(contract_state.do_get_len(), (1, 2)); + assert_eq!(contract_state.do_is_empty(), (false, false)); +} - let empty_list = ListTrait::::fetch(0, storage_address).expect('List fetch failed'); +#[test] +#[available_gas(100000000)] +fn test_fetch_empty_list() { + let storage_address = storage_base_address_from_felt252('empty_address'); - assert_eq!(empty_list.address_domain, 0, "Address domain should be 0"); - assert_eq!(empty_list.len(), 0, "Length should be 0"); - assert_eq!(empty_list.base.into(), storage_address, "Base address mismatch"); - assert_eq!(empty_list.storage_size(), 1, "Storage size should be 1"); - } + let empty_list = ListTrait::::fetch(0, storage_address).expect('List fetch failed'); + assert_eq!(empty_list.address_domain, 0); + assert_eq!(empty_list.len(), 0); + assert_eq!(empty_list.base.into(), storage_address); + assert_eq!(empty_list.storage_size(), 1); +} - #[test] - #[available_gas(100000000)] - fn test_fetch_existing_list() { - let contract = deploy_mock(); - set_contract_address(contract.contract_address); - let contract_state = AListHolder::unsafe_new_contract_state(); - let mock_addr = mock_addr(); - - assert_eq!(contract.do_append(mock_addr, 10), (0, 0), "1st append idx"); - assert_eq!(contract.do_append(mock_addr, 20), (1, 1), "2nd append idx"); - - let addresses_address = contract_state.addresses.address(); - let addresses_list = ListTrait::::fetch(0, addresses_address) - .expect('List fetch failed'); - assert_eq!(addresses_list.address_domain, 0, "Address domain should be 0"); - assert_eq!(addresses_list.len(), 2, "Length should be 2"); - assert_eq!(addresses_list.base.into(), addresses_address, "Base address mismatch"); - assert_eq!(addresses_list.storage_size(), 1, "Storage size should be 1"); - - let numbers_address = contract_state.numbers.address(); - let numbers_list = ListTrait::::fetch(0, numbers_address).expect('List fetch failed'); - assert_eq!(numbers_list.address_domain, 0, "Address domain should be 0"); - assert_eq!(numbers_list.len(), 2, "Length should be 2"); - assert_eq!(numbers_list.base.into(), numbers_address, "Base address mismatch"); - } +#[test] +#[available_gas(100000000)] +fn test_fetch_existing_list() { + let mut contract_state = AListHolder::contract_state_for_testing(); + let mock_addr = mock_addr(); + + assert_eq!(contract_state.do_append(mock_addr, 10), (0, 0)); + assert_eq!(contract_state.do_append(mock_addr, 20), (1, 1)); + + let addresses_address = contract_state.addresses.as_ptr().__storage_pointer_address__; + let addresses_list = ListTrait::::fetch(0, addresses_address) + .expect('List fetch failed'); + assert_eq!(addresses_list.address_domain, 0); + assert_eq!(addresses_list.len(), 2); + assert_eq!(addresses_list.base.into(), addresses_address); + assert_eq!(addresses_list.storage_size(), 1); + + let numbers_address = contract_state.numbers.as_ptr().__storage_pointer_address__; + let numbers_list = ListTrait::::fetch(0, numbers_address).expect('List fetch failed'); + assert_eq!(numbers_list.address_domain, 0); + assert_eq!(numbers_list.len(), 2); + assert_eq!(numbers_list.base.into(), numbers_address); +} - #[test] - #[available_gas(100000000)] - fn test_is_empty() { - let contract = deploy_mock(); +#[test] +#[available_gas(100000000)] +fn test_is_empty() { + let contract = deploy_mock(); - assert_eq!(contract.do_is_empty(), (true, true), "is empty"); - contract.do_append(mock_addr(), 1337); - assert_eq!(contract.do_is_empty(), (false, false), "is not empty"); - } + assert_eq!(contract.do_is_empty(), (true, true)); + contract.do_append(mock_addr(), 1337); + assert_eq!(contract.do_is_empty(), (false, false)); +} - #[test] - #[available_gas(100000000)] - fn test_append_few() { - let contract = deploy_mock(); +#[test] +#[available_gas(100000000)] +fn test_append_few() { + let contract = deploy_mock(); - assert_eq!(contract.do_append(mock_addr(), 10), (0, 0), "1st append idx"); - assert_eq!(contract.do_append(mock_addr(), 20), (1, 1), "2nd append idx"); - assert_eq!(contract.do_get_len(), (2, 2), "len"); - } + assert_eq!(contract.do_append(mock_addr(), 10), (0, 0)); + assert_eq!(contract.do_append(mock_addr(), 20), (1, 1)); + assert_eq!(contract.do_get_len(), (2, 2)); +} - #[test] - #[available_gas(100000000000)] - fn test_append_get_many() { - let contract = deploy_mock(); - let mock_addr = mock_addr(); - - let mut index: u32 = 0; - let max: u32 = 513; - - // test appending many - while (index != max) { - let append_indexes = contract.do_append(mock_addr, index.into()); - assert(append_indexes == (index, index), index.into()); - index += 1; - }; - - assert_eq!(contract.do_get_len(), (max, max), "len"); - - // test getting many - index = 0; - while (index != max) { - let (some_addr, some_number) = contract.do_get(index); - assert!(some_addr.is_some(), "addr is some"); - assert_eq!(some_addr.unwrap(), mock_addr, "addr"); - assert!(some_number.is_some(), "number is some"); - assert_eq!(some_number.unwrap(), index.into(), "number"); - - index += 1; - } - } +#[test] +#[available_gas(100000000000)] +fn test_append_get_many() { + let contract = deploy_mock(); + let mock_addr = mock_addr(); - #[test] - #[available_gas(100000000)] - fn test_get_pass() { - let contract = deploy_mock(); - let mock_addr = mock_addr(); - - contract.do_append(mock_addr, 100); // idx 0 - contract.do_append(mock_addr, 200); // idx 1 - contract.do_append(mock_addr, 300); // idx 2 - - let (some_addr0, some_number0) = contract.do_get(0); - assert!(some_addr0.is_some(), "addr0 is some"); - assert_eq!(some_addr0.unwrap(), mock_addr, "addr0"); - assert!(some_number0.is_some(), "number0 is some"); - assert_eq!(some_number0.unwrap(), 100, "number0"); - - let (some_addr1, some_number1) = contract.do_get(1); - assert!(some_addr1.is_some(), "addr1 is some"); - assert_eq!(some_addr1.unwrap(), mock_addr, "addr1"); - assert!(some_number1.is_some(), "number1 is some"); - assert_eq!(some_number1.unwrap(), 200, "number1"); - - let (some_addr2, some_number2) = contract.do_get(2); - assert!(some_addr2.is_some(), "addr2 is some"); - assert_eq!(some_addr2.unwrap(), mock_addr, "addr2"); - assert!(some_number2.is_some(), "number2 is some"); - assert_eq!(some_number2.unwrap(), 300, "number2"); - } + let mut index: u32 = 0; + let max: u32 = 513; - #[test] - #[available_gas(100000000)] - fn test_get_empty() { - let contract = deploy_mock(); - let (addr, number) = contract.do_get(0); - assert!(addr.is_none(), "addr is none"); - assert!(number.is_none(), "number is none"); - } + // test appending many + while (index != max) { + let append_indexes = contract.do_append(mock_addr, index.into()); + assert_eq!(append_indexes, (index, index)); + index += 1; + }; + + assert_eq!(contract.do_get_len(), (max, max)); - #[test] - #[available_gas(100000000)] - fn test_get_out_of_bounds() { - let contract = deploy_mock(); - contract.do_append(mock_addr(), 10); - let (addr, number) = contract.do_get(42); - assert!(addr.is_none(), "addr is none"); - assert!(number.is_none(), "number is none"); + // test getting many + index = 0; + while (index != max) { + let (some_addr, some_number) = contract.do_get(index); + assert!(some_addr.is_some(), "addr is some"); + assert_eq!(some_addr.unwrap(), mock_addr); + assert!(some_number.is_some(), "number is some"); + assert_eq!(some_number.unwrap(), index.into()); + + index += 1; } +} - #[test] - #[available_gas(100000000)] - fn test_get_index_pass() { - let contract = deploy_mock(); - let mock_addr = mock_addr(); +#[test] +#[available_gas(100000000)] +fn test_get_pass() { + let contract = deploy_mock(); + let mock_addr = mock_addr(); + + contract.do_append(mock_addr, 100); // idx 0 + contract.do_append(mock_addr, 200); // idx 1 + contract.do_append(mock_addr, 300); // idx 2 + + let (some_addr0, some_number0) = contract.do_get(0); + assert!(some_addr0.is_some(), "addr0 is some"); + assert_eq!(some_addr0.unwrap(), mock_addr); + assert!(some_number0.is_some(), "number0 is some"); + assert_eq!(some_number0.unwrap(), 100); + + let (some_addr1, some_number1) = contract.do_get(1); + assert!(some_addr1.is_some(), "addr1 is some"); + assert_eq!(some_addr1.unwrap(), mock_addr); + assert!(some_number1.is_some(), "number1 is some"); + assert_eq!(some_number1.unwrap(), 200); + + let (some_addr2, some_number2) = contract.do_get(2); + assert!(some_addr2.is_some(), "addr2 is some"); + assert_eq!(some_addr2.unwrap(), mock_addr); + assert!(some_number2.is_some(), "number2 is some"); + assert_eq!(some_number2.unwrap(), 300); +} - contract.do_append(mock_addr, 100); // idx 0 - contract.do_append(mock_addr, 200); // idx 1 - contract.do_append(mock_addr, 300); // idx 2 +#[test] +#[available_gas(100000000)] +fn test_get_empty() { + let contract = deploy_mock(); + let (addr, number) = contract.do_get(0); + assert!(addr.is_none(), "addr is none"); + assert!(number.is_none(), "number is none"); +} - assert_eq!(contract.do_get_index(0), (mock_addr, 100), "idx 0"); - assert_eq!(contract.do_get_index(1), (mock_addr, 200), "idx 1"); - assert_eq!(contract.do_get_index(2), (mock_addr, 300), "idx 2"); - } +#[test] +#[available_gas(100000000)] +fn test_get_out_of_bounds() { + let contract = deploy_mock(); + contract.do_append(mock_addr(), 10); + let (addr, number) = contract.do_get(42); + assert!(addr.is_none(), "addr is none"); + assert!(number.is_none(), "number is none"); +} - #[test] - #[available_gas(100000000)] - #[should_panic(expected: ('List index out of bounds', 'ENTRYPOINT_FAILED'))] - fn test_get_index_out_of_bounds() { - let contract = deploy_mock(); - contract.do_append(mock_addr(), 10); - contract.do_get_index(10); - } +#[test] +#[available_gas(100000000)] +fn test_get_index_pass() { + let contract = deploy_mock(); + let mock_addr = mock_addr(); - #[test] - #[available_gas(100000000)] - fn test_set_pass() { - let contract = deploy_mock(); - let mock_addr = mock_addr(); - let diff_addr = starknet::contract_address_const::<'bye'>(); + contract.do_append(mock_addr, 100); // idx 0 + contract.do_append(mock_addr, 200); // idx 1 + contract.do_append(mock_addr, 300); // idx 2 - contract.do_append(mock_addr, 10); - contract.do_append(mock_addr, 20); - contract.do_append(mock_addr, 30); + assert_eq!(contract.do_get_index(0), (mock_addr, 100)); + assert_eq!(contract.do_get_index(1), (mock_addr, 200)); + assert_eq!(contract.do_get_index(2), (mock_addr, 300)); +} - contract.do_set(0, diff_addr, 100); - contract.do_set(2, diff_addr, 300); +#[test] +#[available_gas(100000000)] +#[should_panic(expected: ('List index out of bounds', 'ENTRYPOINT_FAILED'))] +fn test_get_index_out_of_bounds() { + let contract = deploy_mock(); + contract.do_append(mock_addr(), 10); + contract.do_get_index(10); +} - assert_eq!(contract.do_get_index(0), (diff_addr, 100), "new at 0"); - assert_eq!(contract.do_get_index(1), (mock_addr, 20), "old at 1"); - assert_eq!(contract.do_get_index(2), (diff_addr, 300), "new at 2"); - assert_eq!(contract.do_get_len(), (3, 3), "len"); - } +#[test] +#[available_gas(100000000)] +fn test_set_pass() { + let contract = deploy_mock(); + let mock_addr = mock_addr(); + let diff_addr = starknet::contract_address_const::<'bye'>(); - #[test] - #[available_gas(100000000)] - #[should_panic(expected: ('List index out of bounds', 'ENTRYPOINT_FAILED'))] - fn test_set_out_of_bounds() { - let contract = deploy_mock(); - contract.do_set(2, mock_addr(), 20); - } + contract.do_append(mock_addr, 10); + contract.do_append(mock_addr, 20); + contract.do_append(mock_addr, 30); - #[test] - #[available_gas(100000000)] - fn test_pop_front_pass() { - let contract = deploy_mock(); - let mock_addr = mock_addr(); - - contract.do_append(mock_addr, 100); // idx 0 - contract.do_append(mock_addr, 200); // idx 1 - contract.do_append(mock_addr, 300); // idx 2 - - assert_eq!(contract.do_get_len(), (3, 3), "len"); - - let (pop_addr, pop_number) = contract.do_pop_front(); - assert!(pop_addr.is_some(), "pop addr 2 is some"); - assert_eq!(pop_addr.unwrap(), mock_addr, "addr 2"); - assert!(pop_number.is_some(), "pop number 2 is some"); - assert_eq!(pop_number.unwrap(), 300, "number 2"); - assert_eq!(contract.do_get_len(), (2, 2), "len"); - - let (pop_addr, pop_number) = contract.do_pop_front(); - assert!(pop_addr.is_some(), "pop addr 1 is some"); - assert_eq!(pop_addr.unwrap(), mock_addr, "addr 1"); - assert!(pop_number.is_some(), "pop number 1 is some"); - assert_eq!(pop_number.unwrap(), 200, "number 1"); - assert_eq!(contract.do_get_len(), (1, 1), "len"); - - let (pop_addr, pop_number) = contract.do_pop_front(); - assert!(pop_addr.is_some(), "pop addr 0 is some"); - assert_eq!(pop_addr.unwrap(), mock_addr, "addr 0"); - assert!(pop_number.is_some(), "pop number 0 is some"); - assert_eq!(pop_number.unwrap(), 100, "number 0"); - assert_eq!(contract.do_get_len(), (0, 0), "len"); - } + contract.do_set(0, diff_addr, 100); + contract.do_set(2, diff_addr, 300); - #[test] - #[available_gas(100000000)] - fn test_pop_front_empty() { - let contract = deploy_mock(); + assert_eq!(contract.do_get_index(0), (diff_addr, 100)); + assert_eq!(contract.do_get_index(1), (mock_addr, 20)); + assert_eq!(contract.do_get_index(2), (diff_addr, 300)); + assert_eq!(contract.do_get_len(), (3, 3)); +} - let (pop_addr, pop_number) = contract.do_pop_front(); - assert!(pop_addr.is_none(), "pop addr none"); - assert!(pop_number.is_none(), "pop number none"); - } +#[test] +#[available_gas(100000000)] +#[should_panic(expected: ('List index out of bounds', 'ENTRYPOINT_FAILED'))] +fn test_set_out_of_bounds() { + let contract = deploy_mock(); + contract.do_set(2, mock_addr(), 20); +} - #[test] - #[available_gas(100000000)] - fn test_pop_append() { - let contract = deploy_mock(); - // write something - contract.do_append(mock_addr(), 10); - assert_eq!(contract.do_get_len(), (1, 1), "len 1"); - - // pop it - contract.do_pop_front(); - assert_eq!(contract.do_get_len(), (0, 0), "len 2"); - - let diff_addr = starknet::contract_address_const::<'bye'>(); - // append again and check if it overwrites - contract.do_append(diff_addr, 9000); - assert_eq!(contract.do_get_len(), (1, 1), "len 3"); - let (addr, number) = contract.do_get_index(0); - assert_eq!(addr, diff_addr, "addr"); - assert_eq!(number, 9000, "number"); - } +#[test] +#[available_gas(100000000)] +fn test_pop_front_pass() { + let contract = deploy_mock(); + let mock_addr = mock_addr(); + + contract.do_append(mock_addr, 100); // idx 0 + contract.do_append(mock_addr, 200); // idx 1 + contract.do_append(mock_addr, 300); // idx 2 + + assert_eq!(contract.do_get_len(), (3, 3)); + + let (pop_addr, pop_number) = contract.do_pop_front(); + assert!(pop_addr.is_some(), "pop addr 2 is some"); + assert_eq!(pop_addr.unwrap(), mock_addr); + assert!(pop_number.is_some(), "pop number 2 is some"); + assert_eq!(pop_number.unwrap(), 300); + assert_eq!(contract.do_get_len(), (2, 2)); + + let (pop_addr, pop_number) = contract.do_pop_front(); + assert!(pop_addr.is_some(), "pop addr 1 is some"); + assert_eq!(pop_addr.unwrap(), mock_addr); + assert!(pop_number.is_some(), "pop number 1 is some"); + assert_eq!(pop_number.unwrap(), 200); + assert_eq!(contract.do_get_len(), (1, 1)); + + let (pop_addr, pop_number) = contract.do_pop_front(); + assert!(pop_addr.is_some(), "pop addr 0 is some"); + assert_eq!(pop_addr.unwrap(), mock_addr); + assert!(pop_number.is_some(), "pop number 0 is some"); + assert_eq!(pop_number.unwrap(), 100); + assert_eq!(contract.do_get_len(), (0, 0)); +} - #[test] - #[available_gas(100000000)] - fn test_array_pass() { - let contract = deploy_mock(); - let mock_addr = mock_addr(); +#[test] +#[available_gas(100000000)] +fn test_pop_front_empty() { + let contract = deploy_mock(); - contract.do_append(mock_addr, 100); // idx 0 - contract.do_append(mock_addr, 200); // idx 1 - contract.do_append(mock_addr, 300); // idx 2 + let (pop_addr, pop_number) = contract.do_pop_front(); + assert!(pop_addr.is_none(), "pop addr none"); + assert!(pop_number.is_none(), "pop number none"); +} - let (array_addr, array_number) = contract.do_array(); +#[test] +#[available_gas(100000000)] +fn test_pop_append() { + let contract = deploy_mock(); + // write something + contract.do_append(mock_addr(), 10); + assert_eq!(contract.do_get_len(), (1, 1)); + + // pop it + contract.do_pop_front(); + assert_eq!(contract.do_get_len(), (0, 0)); + + let diff_addr = starknet::contract_address_const::<'bye'>(); + // append again and check if it overwrites + contract.do_append(diff_addr, 9000); + assert_eq!(contract.do_get_len(), (1, 1)); + let (addr, number) = contract.do_get_index(0); + assert_eq!(addr, diff_addr); + assert_eq!(number, 9000); +} - assert_eq!((array_addr.len(), array_number.len()), contract.do_get_len(), "lens mismatch"); - assert_eq!((*array_addr[0], *array_number[0]), contract.do_get_index(0), "idx 0"); - assert_eq!((*array_addr[1], *array_number[1]), contract.do_get_index(1), "idx 1"); - assert_eq!((*array_addr[2], *array_number[2]), contract.do_get_index(2), "idx 2"); - } +#[test] +#[available_gas(100000000)] +fn test_array_pass() { + let contract = deploy_mock(); + let mock_addr = mock_addr(); - #[test] - #[available_gas(100000000)] - fn test_array_empty() { - let contract = deploy_mock(); + contract.do_append(mock_addr, 100); // idx 0 + contract.do_append(mock_addr, 200); // idx 1 + contract.do_append(mock_addr, 300); // idx 2 - let (array_addr, array_number) = contract.do_array(); - assert_eq!((array_addr.len(), array_number.len()), (0, 0), "lens must be null"); - } + let (array_addr, array_number) = contract.do_array(); - #[test] - #[available_gas(100000000)] - fn test_array_clean() { - let contract = deploy_mock(); - let mock_addr = mock_addr(); - - contract.do_append(mock_addr, 100); // idx 0 - contract.do_append(mock_addr, 200); // idx 1 - contract.do_append(mock_addr, 300); // idx 2 - contract.do_clean(); - assert_eq!(contract.do_get_len(), (0, 0), "is empty"); - } + assert_eq!((array_addr.len(), array_number.len()), contract.do_get_len()); + assert_eq!((*array_addr[0], *array_number[0]), contract.do_get_index(0)); + assert_eq!((*array_addr[1], *array_number[1]), contract.do_get_index(1)); + assert_eq!((*array_addr[2], *array_number[2]), contract.do_get_index(2)); +} - #[test] - #[available_gas(100000000)] - fn test_array_clean_with_empty_array() { - let contract = deploy_mock(); +#[test] +#[available_gas(100000000)] +fn test_array_empty() { + let contract = deploy_mock(); - assert_eq!(contract.do_get_len(), (0, 0), "is empty"); + let (array_addr, array_number) = contract.do_array(); + assert_eq!((array_addr.len(), array_number.len()), (0, 0)); +} + +#[test] +#[available_gas(100000000)] +fn test_array_clean() { + let contract = deploy_mock(); + let mock_addr = mock_addr(); + + contract.do_append(mock_addr, 100); // idx 0 + contract.do_append(mock_addr, 200); // idx 1 + contract.do_append(mock_addr, 300); // idx 2 + contract.do_clean(); + assert_eq!(contract.do_get_len(), (0, 0)); +} - contract.do_clean(); +#[test] +#[available_gas(100000000)] +fn test_array_clean_with_empty_array() { + let contract = deploy_mock(); - assert_eq!(contract.do_get_len(), (0, 0), "is still empty"); - } + assert_eq!(contract.do_get_len(), (0, 0)); - #[test] - #[available_gas(100000000)] - fn test_array_get_value_after_clean() { - let contract = deploy_mock(); - let mock_addr = mock_addr(); + contract.do_clean(); - contract.do_append(mock_addr, 100); // idx 0 - let (addr, number) = contract.do_get(0); - assert!(addr.is_some(), "addr is some"); - assert_eq!(addr.unwrap(), mock_addr, "should be mock_addr"); - assert!(number.is_some(), "number is some"); - assert_eq!(number.unwrap(), 100, "should be 100"); + assert_eq!(contract.do_get_len(), (0, 0)); +} - contract.do_clean(); +#[test] +#[available_gas(100000000)] +fn test_array_get_value_after_clean() { + let contract = deploy_mock(); + let mock_addr = mock_addr(); - assert_eq!(contract.do_get_len(), (0, 0), "len"); + contract.do_append(mock_addr, 100); // idx 0 + let (addr, number) = contract.do_get(0); + assert!(addr.is_some(), "addr is some"); + assert_eq!(addr.unwrap(), mock_addr); + assert!(number.is_some(), "number is some"); + assert_eq!(number.unwrap(), 100); - let (addr, number) = contract.do_get(0); - assert!(addr.is_none(), "addr is none"); - assert!(number.is_none(), "number is none"); - } + contract.do_clean(); - #[test] - #[available_gas(100000000)] - fn test_append_array_empty() { - let contract = deploy_mock(); + assert_eq!(contract.do_get_len(), (0, 0)); - contract.do_append_span(array![], array![]); - assert_eq!(contract.do_is_empty(), (true, true), "should be empty"); - } + let (addr, number) = contract.do_get(0); + assert!(addr.is_none(), "addr is none"); + assert!(number.is_none(), "number is none"); +} - #[test] - #[available_gas(100000000)] - fn test_append_span_existing_list() { - let contract = deploy_mock(); - let mock_addr = mock_addr(); - - assert_eq!(contract.do_append(mock_addr, 10), (0, 0), "1st append idx"); - assert_eq!(contract.do_append(mock_addr, 20), (1, 1), "2nd append idx"); - assert_eq!(contract.do_get_len(), (2, 2), "len"); - assert_eq!(contract.do_get_index(0), (mock_addr, 10), "idx 0"); - assert_eq!(contract.do_get_index(1), (mock_addr, 20), "idx 1"); - - contract.do_append_span(array![mock_addr], array![30]); - let (a, b) = contract.do_get_len(); - assert_eq!((a, b), (3, 3), "len"); - - assert_eq!(contract.do_get_index(0), (mock_addr, 10), "idx 0"); - assert_eq!(contract.do_get_index(1), (mock_addr, 20), "idx 1"); - assert_eq!(contract.do_get_index(2), (mock_addr, 30), "idx 2"); - } +#[test] +#[available_gas(100000000)] +fn test_append_array_empty() { + let contract = deploy_mock(); + + contract.do_append_span(array![], array![]); + assert_eq!(contract.do_is_empty(), (true, true)); +} + +#[test] +#[available_gas(100000000)] +fn test_append_span_existing_list() { + let contract = deploy_mock(); + let mock_addr = mock_addr(); + + assert_eq!(contract.do_append(mock_addr, 10), (0, 0)); + assert_eq!(contract.do_append(mock_addr, 20), (1, 1)); + assert_eq!(contract.do_get_len(), (2, 2)); + assert_eq!(contract.do_get_index(0), (mock_addr, 10)); + assert_eq!(contract.do_get_index(1), (mock_addr, 20)); + + contract.do_append_span(array![mock_addr], array![30]); + let (a, b) = contract.do_get_len(); + assert_eq!((a, b), (3, 3)); + + assert_eq!(contract.do_get_index(0), (mock_addr, 10)); + assert_eq!(contract.do_get_index(1), (mock_addr, 20)); + assert_eq!(contract.do_get_index(2), (mock_addr, 30)); }