diff --git a/crates/contracts/src/storage.cairo b/crates/contracts/src/storage.cairo index c2501e69d..3f047b1a8 100644 --- a/crates/contracts/src/storage.cairo +++ b/crates/contracts/src/storage.cairo @@ -18,7 +18,7 @@ pub struct StorageBytecode { const BYTES_PER_FELT: NonZero = 31; -/// An implamentation of the `Store` trait for our specific `StorageBytecode` type. +/// An implementation of the `Store` trait for our specific `StorageBytecode` type. /// The packing-unpacking is done inside the `read` and `write` methods, thus transparent to the /// user. /// The bytecode is stored sequentially, starting from storage address 0, for compatibility purposes @@ -38,13 +38,13 @@ impl StoreBytecode of Store { // afterwards. let base: felt252 = 0; let mut packed_bytecode = array![]; - let mut i = 0; - while i != (chunks_count + 1) { - let storage_address: StorageAddress = (base + i.into()).try_into().unwrap(); - let chunk = storage_read_syscall(address_domain, storage_address).unwrap(); - packed_bytecode.append(chunk); - i += 1; - }; + for i in 0 + ..chunks_count + + 1 { + let storage_address: StorageAddress = (base + i.into()).try_into().unwrap(); + let chunk = storage_read_syscall(address_domain, storage_address).unwrap(); + packed_bytecode.append(chunk); + }; let bytecode = load_packed_bytes(packed_bytecode.span(), bytecode_len); SyscallResult::Ok(StorageBytecode { bytecode: bytecode.span() }) } @@ -131,10 +131,8 @@ mod tests { fn test_store_bytecode_multiple_chunks() { let mut state = account_contract_state(); let mut bytecode_array = array![]; - let mut i = 0; - while i != 100 { + for i in 0..100_u8 { bytecode_array.append(i); - i += 1; }; let bytecode = bytecode_array.span(); // Write the bytecode to the storage diff --git a/crates/evm/src/backend/starknet_backend.cairo b/crates/evm/src/backend/starknet_backend.cairo index c5cba92c7..dba29c576 100644 --- a/crates/evm/src/backend/starknet_backend.cairo +++ b/crates/evm/src/backend/starknet_backend.cairo @@ -138,7 +138,7 @@ pub fn fetch_balance(self: @Address) -> u256 { /// `Ok(())` if the commit was successful, otherwise an `EVMError`. fn commit_accounts(ref state: State) -> Result<(), EVMError> { let mut account_keys = state.accounts.keyset.to_span(); - while let Option::Some(evm_address) = account_keys.pop_front() { + for evm_address in account_keys { let account = state.accounts.changes.get(*evm_address).deref(); commit_account(@account, ref state); }; @@ -231,7 +231,7 @@ fn emit_events(ref self: State) -> Result<(), EVMError> { /// commit_storage MUST be called after commit_accounts. fn commit_storage(ref self: State) -> Result<(), EVMError> { let mut storage_keys = self.accounts_storage.keyset.to_span(); - while let Option::Some(state_key) = storage_keys.pop_front() { + for state_key in storage_keys { let (evm_address, key, value) = self.accounts_storage.changes.get(*state_key).deref(); let mut account = self.get_account(evm_address); // @dev: EIP-6780 - If selfdestruct on an account created, dont commit data diff --git a/crates/evm/src/instructions/duplication_operations.cairo b/crates/evm/src/instructions/duplication_operations.cairo index db322d326..5752279ba 100644 --- a/crates/evm/src/instructions/duplication_operations.cairo +++ b/crates/evm/src/instructions/duplication_operations.cairo @@ -123,25 +123,20 @@ mod tests { // ensures all values start from index `from` upto index `to` of stack are `0x0` fn ensures_zeros(ref stack: Stack, from: u32, to: u32) { - let mut idx: u32 = from; - if to > from { return; } - while idx != to { + for idx in from..to { assert(stack.peek_at(idx).unwrap() == 0x00, 'should be zero'); - idx += 1; }; } // push `n` number of `0x0` to the stack fn push_zeros(ref stack: Stack, n: u8) { - let mut i = 0; - while i != n { + for _ in 0..n { stack.push(0x0).unwrap(); - i += 1; - } + }; } #[test] diff --git a/crates/evm/src/instructions/environmental_information.cairo b/crates/evm/src/instructions/environmental_information.cairo index 2661198fa..bcb0729f0 100644 --- a/crates/evm/src/instructions/environmental_information.cairo +++ b/crates/evm/src/instructions/environmental_information.cairo @@ -90,10 +90,8 @@ pub impl EnvironmentInformationImpl of EnvironmentInformationTrait { // Fill the rest of the data to load with zeros // TODO: optimize once we have dw-based exponentiation - let mut i = 32 - bytes_len; - while i != 0 { + for _ in 0..32 - bytes_len { data_to_load *= 256; - i -= 1; }; self.stack.push(data_to_load) } @@ -652,21 +650,22 @@ mod tests { // Memory initialization with a value to verify that if the offset + size is out of the // bound bytes, 0's have been copied. // Otherwise, the memory value would be 0, and we wouldn't be able to check it. - let mut i = 0; - while i != (size / 32) + 1 { - vm - .memory - .store( - 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, - dest_offset + (i * 32) - ); - - let initial: u256 = vm.memory.load_internal(dest_offset + (i * 32)).into(); - - assert_eq!(initial, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF); - - i += 1; - }; + for i in 0 + ..(size / 32) + + 1 { + vm + .memory + .store( + 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF, + dest_offset + (i * 32) + ); + + let initial: u256 = vm.memory.load_internal(dest_offset + (i * 32)).into(); + + assert_eq!( + initial, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF + ); + }; // When vm.exec_calldatacopy().expect('exec_calldatacopy failed'); @@ -775,17 +774,15 @@ mod tests { let result: u256 = vm.memory.load_internal(dest_offset).into(); let mut results: Array = u256_to_bytes_array(result); - let mut i = 0; - while i != size { - // For out of bound bytes, 0s will be copied. - if (i + offset >= bytecode.len()) { - assert_eq!(*results[i], 0); - } else { - assert_eq!(*results[i], *bytecode[i + offset]); - } - - i += 1; - }; + for i in 0 + ..size { + // For out of bound bytes, 0s will be copied. + if (i + offset >= bytecode.len()) { + assert_eq!(*results[i], 0); + } else { + assert_eq!(*results[i], *bytecode[i + offset]); + } + }; } // ************************************************************************* diff --git a/crates/evm/src/instructions/push_operations.cairo b/crates/evm/src/instructions/push_operations.cairo index 31a53a698..d6bd057cb 100644 --- a/crates/evm/src/instructions/push_operations.cairo +++ b/crates/evm/src/instructions/push_operations.cairo @@ -333,9 +333,8 @@ mod tests { fn get_n_0xFF(mut n: u8) -> Span { let mut array: Array = ArrayTrait::new(); array.append(0x00); - while n != 0 { + for _ in 0..n { array.append(0xFF); - n -= 1; }; array.span() } diff --git a/crates/evm/src/instructions/sha3.cairo b/crates/evm/src/instructions/sha3.cairo index e04e36590..563a5fa12 100644 --- a/crates/evm/src/instructions/sha3.cairo +++ b/crates/evm/src/instructions/sha3.cairo @@ -102,17 +102,17 @@ fn compute_memory_words_amount(size: u32, offset: u32, mem_len: u32) -> (u32, u3 fn fill_array_with_memory_words( ref self: VM, ref to_hash: Array, mut offset: u32, mut amount: u32 ) -> u32 { - while amount != 0 { - let loaded = self.memory.load(offset); - let ((high_h, low_h), (high_l, low_l)) = loaded.split_into_u64_le(); - to_hash.append(low_h); - to_hash.append(high_h); - to_hash.append(low_l); - to_hash.append(high_l); - - offset += 32; - amount -= 1; - }; + for _ in 0 + ..amount { + let loaded = self.memory.load(offset); + let ((high_h, low_h), (high_l, low_l)) = loaded.split_into_u64_le(); + to_hash.append(low_h); + to_hash.append(high_h); + to_hash.append(low_l); + to_hash.append(high_l); + + offset += 32; + }; offset } diff --git a/crates/evm/src/memory.cairo b/crates/evm/src/memory.cairo index b24ec7ca7..601fc1bbc 100644 --- a/crates/evm/src/memory.cairo +++ b/crates/evm/src/memory.cairo @@ -369,12 +369,12 @@ pub(crate) impl InternalMemoryMethods of InternalMemoryTrait { fn load_aligned_words( ref self: Memory, mut chunk_index: usize, final_chunk: usize, ref elements: Array ) { - while chunk_index != final_chunk { - let value = self.items.get(chunk_index.into()); - // Pushes 16 items to `elements` - helpers::split_word_128(value.into(), ref elements); - chunk_index += 1; - } + for i in chunk_index + ..final_chunk { + let value = self.items.get(i.into()); + // Pushes 16 items to `elements` + helpers::split_word_128(value.into(), ref elements); + }; } /// Loads a `u256` element from the memory chunk at a specified offset. @@ -810,10 +810,8 @@ mod tests { memory.load_n_internal(16, ref results, 0); assert(results.len() == 16, 'error'); - let mut i = 0; - while i != results.len() { - assert(*results[i] == 0xFF, 'byte value loaded not correct'); - i += 1; + for result in results { + assert(result == 0xFF, 'byte value loaded not correct'); } } diff --git a/crates/evm/src/precompiles.cairo b/crates/evm/src/precompiles.cairo index a467a7b60..ff8dd9386 100644 --- a/crates/evm/src/precompiles.cairo +++ b/crates/evm/src/precompiles.cairo @@ -39,12 +39,11 @@ pub const FIRST_ROLLUP_PRECOMPILE_ADDRESS: u256 = 0x100; /// * `Set` - A set containing all Ethereum precompile addresses. pub fn eth_precompile_addresses() -> Set { let mut precompile_addresses: Array = array![]; - //TODO(2.8) use range operator - let mut i = FIRST_ETHEREUM_PRECOMPILE_ADDRESS; - while i <= LAST_ETHEREUM_PRECOMPILE_ADDRESS { - precompile_addresses.append(i.try_into().unwrap()); - i = i + 1; - }; + for i in FIRST_ETHEREUM_PRECOMPILE_ADDRESS + ..LAST_ETHEREUM_PRECOMPILE_ADDRESS + + 0x01 { + precompile_addresses.append(i.try_into().unwrap()); + }; SetTrait::from_array(precompile_addresses) } diff --git a/crates/evm/src/precompiles/blake2f.cairo b/crates/evm/src/precompiles/blake2f.cairo index 94ecdd935..ac16b81d2 100644 --- a/crates/evm/src/precompiles/blake2f.cairo +++ b/crates/evm/src/precompiles/blake2f.cairo @@ -39,22 +39,18 @@ pub impl Blake2f of Precompile { let mut h: Array = Default::default(); let mut m: Array = Default::default(); - let mut i = 0; let mut pos = 4; - while i != 8 { + for _ in 0..8_u8 { // safe unwrap, because we have made sure of the input length to be 213 h.append(input.slice(pos, 8).from_le_bytes().unwrap()); - i += 1; pos += 8; }; - let mut i = 0; let mut pos = 68; - while i != 16 { + for _ in 0..16_u8 { // safe unwrap, because we have made sure of the input length to be 213 m.append(input.slice(pos, 8).from_le_bytes().unwrap()); - i += 1; - pos += 8; + pos += 8 }; let mut t: Array = Default::default(); @@ -68,12 +64,9 @@ pub impl Blake2f of Precompile { let mut return_data: Array = Default::default(); - let mut i = 0; - while i != res.len() { - let bytes = (*res[i]).to_le_bytes_padded(); + for result in res { + let bytes = (*result).to_le_bytes_padded(); return_data.append_span(bytes); - - i += 1; }; Result::Ok((gas, return_data.span())) diff --git a/crates/evm/src/precompiles/ec_operations/ec_mul.cairo b/crates/evm/src/precompiles/ec_operations/ec_mul.cairo index 6c94d7d97..814d7e0e4 100644 --- a/crates/evm/src/precompiles/ec_operations/ec_mul.cairo +++ b/crates/evm/src/precompiles/ec_operations/ec_mul.cairo @@ -117,7 +117,7 @@ fn get_bits_little(s: u256) -> Array { fn ec_mul_inner(pt: (u384, u384), mut bits: Array) -> Option<(u384, u384)> { let (mut temp_x, mut temp_y) = pt; let mut result: Option<(u384, u384)> = Option::None; - while let Option::Some(bit) = bits.pop_front() { + for bit in bits { if bit != 0 { match result { Option::Some((xr, yr)) => result = ec_safe_add(temp_x, temp_y, xr, yr), diff --git a/crates/evm/src/stack.cairo b/crates/evm/src/stack.cairo index 06e7896f7..506e87d9f 100644 --- a/crates/evm/src/stack.cairo +++ b/crates/evm/src/stack.cairo @@ -208,9 +208,8 @@ impl StackImpl of StackTrait { fn pop_n(ref self: Stack, mut n: usize) -> Result, EVMError> { ensure(!(n > self.len()), EVMError::StackUnderflow)?; let mut popped_items = ArrayTrait::::new(); - while n != 0 { + for _ in 0..n { popped_items.append(self.pop().unwrap()); - n -= 1; }; Result::Ok(popped_items) } @@ -346,11 +345,9 @@ mod tests { fn test_should_fail_when_overflow() { // Given let mut stack = StackTrait::new(); - let mut i = 0; // When - while i != constants::STACK_MAX_DEPTH { - i += 1; + for _ in 0..constants::STACK_MAX_DEPTH { stack.push(1).unwrap(); }; diff --git a/crates/evm/src/state.cairo b/crates/evm/src/state.cairo index 1dd6fde36..0ea8ce3ca 100644 --- a/crates/evm/src/state.cairo +++ b/crates/evm/src/state.cairo @@ -93,7 +93,7 @@ impl StateChangeLogImpl, +Copy> of StateChangeLogTrait { fn clone(ref self: StateChangeLog) -> StateChangeLog { let mut cloned_changes = Default::default(); let mut keyset_span = self.keyset.to_span(); - while let Option::Some(key) = keyset_span.pop_front() { + for key in keyset_span { let value = self.changes.get(*key).deref(); cloned_changes.insert(*key, NullableTrait::new(value)); }; diff --git a/crates/snforge_utils/src/lib.cairo b/crates/snforge_utils/src/lib.cairo index 9809c2aec..0588fe66c 100644 --- a/crates/snforge_utils/src/lib.cairo +++ b/crates/snforge_utils/src/lib.cairo @@ -216,36 +216,35 @@ pub mod snforge_utils { fn build(self: @EventsFilter) -> ContractEvents { let events = (*self.events.events).span(); let mut filtered_events = array![]; - let mut i = 0; - while i < events.len() { - let (from, event) = events.at(i).clone(); - let mut include = true; + for i in 0 + ..events + .len() { + let (from, event) = events.at(i).clone(); + let mut include = true; - if let Option::Some(addr) = self.contract_address { - if from != *addr { - include = false; - } - } - - if include && self.key_filter.is_some() { - if !(event.keys.span() == (*self.key_filter).unwrap()) { - include = false; - } - } + if let Option::Some(addr) = self.contract_address { + if from != *addr { + include = false; + } + } - if include && self.data_filter.is_some() { - if !event.data.includes((*self.data_filter).unwrap()) { - include = false; - } - } + if include && self.key_filter.is_some() { + if !(event.keys.span() == (*self.key_filter).unwrap()) { + include = false; + } + } - if include { - filtered_events.append(event.clone()); - } + if include && self.data_filter.is_some() { + if !event.data.includes((*self.data_filter).unwrap()) { + include = false; + } + } - i += 1; - }; + if include { + filtered_events.append(event.clone()); + } + }; ContractEvents { events: filtered_events } } @@ -268,16 +267,17 @@ pub mod snforge_utils { let mut expected_data = array![]; event.append_keys_and_data(ref expected_keys, ref expected_data); - let mut i = 0; let mut found = false; - while i < self.events.len() { - let event = self.events.at(i); - if event.keys == @expected_keys && event.data == @expected_data { - found = true; - break; - } - i += 1; - }; + for i in 0 + ..self + .events + .len() { + let event = self.events.at(i); + if event.keys == @expected_keys && event.data == @expected_data { + found = true; + break; + } + }; assert(found, 'Expected event was not emitted'); } @@ -289,15 +289,16 @@ pub mod snforge_utils { let mut expected_data = array![]; event.append_keys_and_data(ref expected_keys, ref expected_data); - let mut i = 0; - while i < self.events.len() { - let event = self.events.at(i); - assert( - event.keys != @expected_keys || event.data != @expected_data, - 'Unexpected event was emitted' - ); - i += 1; - } + for i in 0 + ..self + .events + .len() { + let event = self.events.at(i); + assert( + event.keys != @expected_keys || event.data != @expected_data, + 'Unexpected event was emitted' + ); + } } } @@ -305,12 +306,14 @@ pub mod snforge_utils { pub fn store_evm(target: Address, evm_key: u256, evm_value: u256) { let storage_address = compute_storage_key(target.evm, evm_key); let serialized_value = [evm_value.low.into(), evm_value.high.into()].span(); - let mut offset: usize = 0; - while offset != serialized_value.len() { - store_felt252( - target.starknet, storage_address + offset.into(), *serialized_value.at(offset) - ); - offset += 1; - } + for offset in 0 + ..serialized_value + .len() { + store_felt252( + target.starknet, + storage_address + offset.into(), + *serialized_value.at(offset) + ); + }; } } diff --git a/crates/utils/src/crypto/blake2_compress.cairo b/crates/utils/src/crypto/blake2_compress.cairo index 4ce2840e4..e008e7271 100644 --- a/crates/utils/src/crypto/blake2_compress.cairo +++ b/crates/utils/src/crypto/blake2_compress.cairo @@ -70,10 +70,8 @@ fn rotate_right(value: u64, n: u32) -> u64 { /// updated state vector pub fn compress(rounds: usize, h: Span, m: Span, t: Span, f: bool) -> Span { let mut v = VecTrait::::new(); - let mut i = 0; - while i != 16 { + for _ in 0..16_u8 { v.push(0); - i += 1; }; let IV = IV(); diff --git a/crates/utils/src/eth_transaction/eip2930.cairo b/crates/utils/src/eth_transaction/eip2930.cairo index 2766720a9..d59ed6be3 100644 --- a/crates/utils/src/eth_transaction/eip2930.cairo +++ b/crates/utils/src/eth_transaction/eip2930.cairo @@ -17,7 +17,7 @@ pub impl AccessListItemImpl of AccessListItemTrait { let AccessListItem { ethereum_address, mut storage_keys } = *self; let mut storage_keys_arr = array![]; - while let Option::Some(storage_key) = storage_keys.pop_front() { + for storage_key in storage_keys { storage_keys_arr.append((ethereum_address, *storage_key)); }; diff --git a/crates/utils/src/felt_vec.cairo b/crates/utils/src/felt_vec.cairo index 82706e75d..cff02ceb0 100644 --- a/crates/utils/src/felt_vec.cairo +++ b/crates/utils/src/felt_vec.cairo @@ -56,17 +56,16 @@ pub impl Felt252VecTraitImpl< /// * A Span representing bytes conversion of `self` in little endian format fn to_le_bytes(ref self: Felt252Vec) -> Span { let mut res: Array = array![]; - let mut i = 0; - - while i != self.len() { - if self[i] == Zero::zero() { - res.append(Zero::zero()); - } else { - res.append_span(self[i].to_le_bytes()); - } - i += 1; - }; + for i in 0 + ..self + .len() { + if self[i] == Zero::zero() { + res.append(Zero::zero()); + } else { + res.append_span(self[i].to_le_bytes()); + } + }; res.span() } @@ -214,10 +213,8 @@ pub impl Felt252VecTraitImpl< } let stop = idx + vec.len(); - let mut i = idx; - while i != stop { + for i in idx..stop { self.set(i, vec[i - idx]); - i += 1; }; Result::Ok(()) @@ -266,11 +263,8 @@ pub impl Felt252VecTraitImpl< fn duplicate(ref self: Felt252Vec) -> Felt252Vec { let mut new_vec = Default::default(); - let mut i: u32 = 0; - - while i != self.len { + for i in 0..self.len { new_vec.push(self[i]); - i += 1; }; new_vec @@ -297,12 +291,8 @@ pub impl Felt252VecTraitImpl< fn clone_slice(ref self: Felt252Vec, idx: usize, len: usize) -> Felt252Vec { let mut new_vec = Default::default(); - let mut i: u32 = 0; - - while i != len { + for i in 0..len { new_vec.push(self[idx + i]); - - i += 1; }; new_vec @@ -328,14 +318,12 @@ pub impl Felt252VecTraitImpl< return false; }; - let mut i = 0; let mut result = true; - while i != lhs.len() { + for i in 0..lhs.len() { if lhs[i] != rhs[i] { result = false; break; } - i += 1; }; result } @@ -368,11 +356,8 @@ pub impl Felt252VecTraitImpl< return Result::Err(Felt252VecTraitErrors::Overflow); } - let mut i = start_idx; - while i != start_idx + len { + for i in start_idx..start_idx + len { self.set(i, value); - - i += 1; }; Result::Ok(()) diff --git a/crates/utils/src/helpers.cairo b/crates/utils/src/helpers.cairo index d10b7ad6d..d50eb3418 100644 --- a/crates/utils/src/helpers.cairo +++ b/crates/utils/src/helpers.cairo @@ -87,10 +87,9 @@ pub fn split_word(mut value: u256, mut len: usize, ref dst: Array) { /// * `value` - The u128 value to split into bytes /// * `len` - The number of bytes to split the value into pub fn split_u128_le(ref dest: Array, mut value: u128, mut len: usize) { - while len != 0 { + for _ in 0..len { dest.append((value % 256).try_into().unwrap()); value /= 256; - len -= 1; }; } @@ -137,13 +136,13 @@ pub fn load_word(mut len: usize, words: Span) -> u256 { let mut current: u256 = 0; let mut counter = 0; - while len != 0 { - let loaded: u8 = *words[counter]; - let tmp = current * 256; - current = tmp + loaded.into(); - len -= 1; - counter += 1; - }; + for _ in 0 + ..len { + let loaded: u8 = *words[counter]; + let tmp = current * 256; + current = tmp + loaded.into(); + counter += 1; + }; current } @@ -156,22 +155,20 @@ pub fn load_word(mut len: usize, words: Span) -> u256 { /// # Returns /// An `Array` representing the big-endian byte representation of the input value. pub fn u256_to_bytes_array(mut value: u256) -> Array { - let mut counter = 0; let mut bytes_arr: Array = ArrayTrait::new(); // low part - while counter != 16 { - bytes_arr.append((value.low & 0xFF).try_into().unwrap()); - value.low /= 256; - counter += 1; - }; + for _ in 0 + ..16_u8 { + bytes_arr.append((value.low & 0xFF).try_into().unwrap()); + value.low /= 256; + }; - let mut counter = 0; // high part - while counter != 16 { - bytes_arr.append((value.high & 0xFF).try_into().unwrap()); - value.high /= 256; - counter += 1; - }; + for _ in 0 + ..16_u8 { + bytes_arr.append((value.high & 0xFF).try_into().unwrap()); + value.high /= 256; + }; // Reverse the array as memory is arranged in big endian order. let mut counter = bytes_arr.len(); @@ -277,11 +274,8 @@ mod tests { // 16 bytes values let mut arr6 = ArrayTrait::new(); - arr6.append(0xff); - let mut counter: u128 = 0; - while counter < 15 { + for _ in 0..16_u8 { arr6.append(0xff); - counter += 1; }; let res6 = helpers::load_word(16, arr6.span()); assert(340282366920938463463374607431768211455 == res6, 'res6: wrong load'); @@ -319,10 +313,8 @@ mod tests { assert(res4.len() == 16, 'res4: wrong length'); assert(*res4[0] == 0xfe, 'res4: wrong MSB value'); - let mut counter: usize = 1; - while counter < 16 { + for counter in 1..16_u32 { assert(*res4[counter] == 0xff, 'res4: wrong value at index'); - counter += 1; }; } @@ -360,11 +352,9 @@ mod tests { let mut dst4: Array = ArrayTrait::new(); helpers::split_word(max_u128, 16, ref dst4); assert(dst4.len() == 16, 'dst4: wrong length'); - let mut counter: usize = 0; assert(*dst4[15] == 0xfe, 'dst4: wrong LSB value'); - while counter < 15 { + for counter in 0..dst4.len() - 1 { assert_eq!(*dst4[counter], 0xff); - counter += 1; }; } } diff --git a/crates/utils/src/rlp.cairo b/crates/utils/src/rlp.cairo index 513fd52a9..9c991671e 100644 --- a/crates/utils/src/rlp.cairo +++ b/crates/utils/src/rlp.cairo @@ -100,7 +100,7 @@ pub impl RLPImpl of RLPTrait { /// * If encoding a long sequence (should not happen in current implementation) fn encode_sequence(mut input: Span) -> Span { let mut joined_encodings: Array = Default::default(); - while let Option::Some(item) = input.pop_front() { + for item in input { match item { RLPItem::String(string) => { joined_encodings.append_span(Self::encode_string(*string)); diff --git a/crates/utils/src/serialization.cairo b/crates/utils/src/serialization.cairo index 34939f43b..371f9dd1c 100644 --- a/crates/utils/src/serialization.cairo +++ b/crates/utils/src/serialization.cairo @@ -95,22 +95,19 @@ pub fn serialize_transaction_signature( /// /// * `Option>` - The deserialized bytes if successful, or None if deserialization fails. pub fn deserialize_bytes(self: Span) -> Option> { - let mut i = 0; let mut bytes: Array = Default::default(); - while i != self.len() { - let v: Option = (*self[i]).try_into(); + for item in self { + let v: Option = (*item).try_into(); match v { Option::Some(v) => { bytes.append(v); }, Option::None => { break; } } - - i += 1; }; // it means there was an error in the above loop - if (i != self.len()) { + if (bytes.len() != self.len()) { Option::None } else { Option::Some(bytes) @@ -129,13 +126,9 @@ pub fn deserialize_bytes(self: Span) -> Option> { pub fn serialize_bytes(self: Span) -> Array { let mut array: Array = Default::default(); - let mut i = 0; - - while i != self.len() { - let value: felt252 = (*self[i]).into(); + for item in self { + let value: felt252 = (*item).into(); array.append(value); - - i += 1; }; array diff --git a/crates/utils/src/traits.cairo b/crates/utils/src/traits.cairo index 3cf2fbf2f..e5bfc3eb8 100644 --- a/crates/utils/src/traits.cairo +++ b/crates/utils/src/traits.cairo @@ -106,12 +106,11 @@ pub impl SpanU8TryIntoResultEthAddress of TryIntoResult, EthAddress> { ensure(!(len > 20), EVMError::TypeConversionError(TYPE_CONVERSION_ERROR))?; let offset: u32 = len.into() - 1; let mut result: u256 = 0; - let mut i: u32 = 0; - while i != len { - let byte: u256 = (*self.at(i)).into(); - result += byte.shl(8 * (offset - i).into()); - i += 1; - }; + for i in 0 + ..len { + let byte: u256 = (*self.at(i)).into(); + result += byte.shl(8 * (offset - i).into()); + }; let address: felt252 = result.try_into_result()?; Result::Ok(address.try_into().unwrap()) diff --git a/crates/utils/src/traits/array.cairo b/crates/utils/src/traits/array.cairo index 44a2bcb62..35b3669f7 100644 --- a/crates/utils/src/traits/array.cairo +++ b/crates/utils/src/traits/array.cairo @@ -39,10 +39,8 @@ pub impl ArrayExtension> of ArrayExtTrait { /// * `value` - The value to append. /// * `n` - The number of times to append the value. fn append_n<+Copy>(ref self: Array, value: T, mut n: usize) { - while n != 0 { + for _ in 0..n { self.append(value); - - n -= 1; }; } diff --git a/crates/utils/src/traits/bytes.cairo b/crates/utils/src/traits/bytes.cairo index c780098f2..6cec31aee 100644 --- a/crates/utils/src/traits/bytes.cairo +++ b/crates/utils/src/traits/bytes.cairo @@ -59,22 +59,21 @@ pub impl U8SpanExImpl of U8SpanExTrait { // Fill the last input word let mut last_input_word: u64 = 0; - let mut byte_counter: u8 = 0; // We enter a second loop for clarity. // O(2n) should be okay // We might want to regroup every computation into a single loop with appropriate `if` // branching For optimisation - while byte_counter.into() != last_input_num_bytes { - last_input_word += match self.get(full_u64_word_count * 8 + byte_counter.into()) { - Option::Some(byte) => { - let byte: u64 = (*byte.unbox()).into(); - byte.shl(8_u64 * byte_counter.into()) - }, - Option::None => { break; }, + for byte_counter in 0 + ..last_input_num_bytes { + last_input_word += match self.get(full_u64_word_count * 8 + byte_counter.into()) { + Option::Some(byte) => { + let byte: u64 = (*byte.unbox()).into(); + byte.shl(8_u64 * byte_counter.into()) + }, + Option::None => { break; }, + }; }; - byte_counter += 1; - }; (u64_words, last_input_word, last_input_num_bytes) } @@ -183,10 +182,8 @@ pub impl U8SpanExImpl of U8SpanExTrait { }; // append the data - let mut i = 0; - while i != self.len() { - arr.append(*self[i]); - i += 1; + for item in self { + arr.append(*item); }; arr.span() @@ -257,12 +254,11 @@ pub impl ToBytesImpl< let mask = Bounded::::MAX.into(); let mut bytes: Array = Default::default(); - let mut i: u8 = 0; - while i != bytes_used { - let val = Bitshift::::shr(self, eight * (bytes_used - i - 1).into()); - bytes.append((val & mask).try_into().unwrap()); - i += 1; - }; + for i in 0 + ..bytes_used { + let val = Bitshift::::shr(self, eight * (bytes_used - i - 1).into()); + bytes.append((val & mask).try_into().unwrap()); + }; bytes.span() } @@ -283,12 +279,11 @@ pub impl ToBytesImpl< let mut bytes: Array = Default::default(); - let mut i: u8 = 0; - while i != bytes_used { - let val = self.shr(eight * i.into()); - bytes.append((val & mask).try_into().unwrap()); - i += 1; - }; + for i in 0 + ..bytes_used { + let val = self.shr(eight * i.into()); + bytes.append((val & mask).try_into().unwrap()); + }; bytes.span() } @@ -450,29 +445,27 @@ pub impl ByteArrayExt of ByteArrayExTrait { let (nb_full_words, pending_word_len) = DivRem::div_rem( bytes.len(), 31_u32.try_into().unwrap() ); - let mut i = 0; - while i != nb_full_words { - let mut word: felt252 = 0; - let mut j = 0; - while j != 31 { - word = word * POW_256_1.into() + (*bytes.pop_front().unwrap()).into(); - j += 1; + for _ in 0 + ..nb_full_words { + let mut word: felt252 = 0; + for _ in 0 + ..31_u8 { + word = word * POW_256_1.into() + (*bytes.pop_front().unwrap()).into(); + }; + arr.append_word(word.try_into().unwrap(), 31); }; - arr.append_word(word.try_into().unwrap(), 31); - i += 1; - }; if pending_word_len == 0 { return arr; }; let mut pending_word: felt252 = 0; - let mut i = 0; - while i != pending_word_len { - pending_word = pending_word * POW_256_1.into() + (*bytes.pop_front().unwrap()).into(); - i += 1; - }; + for _ in 0 + ..pending_word_len { + pending_word = pending_word * POW_256_1.into() + + (*bytes.pop_front().unwrap()).into(); + }; arr.append_word(pending_word.try_into().unwrap(), pending_word_len); arr } @@ -493,11 +486,8 @@ pub impl ByteArrayExt of ByteArrayExTrait { /// * A Span containing the bytes from the ByteArray fn into_bytes(self: ByteArray) -> Span { let mut output: Array = Default::default(); - let len = self.len(); - let mut i = 0; - while i != len { + for i in 0..self.len() { output.append(self[i]); - i += 1; }; output.span() } @@ -545,22 +535,22 @@ pub impl ByteArrayExt of ByteArrayExTrait { // Fill the last input word let mut last_input_word: u64 = 0; - let mut byte_counter: u8 = 0; // We enter a second loop for clarity. // O(2n) should be okay // We might want to regroup every computation into a single loop with appropriate `if` // branching For optimisation - while byte_counter.into() != last_input_num_bytes { - last_input_word += match self.at(full_u64_word_count * 8 + byte_counter.into()) { - Option::Some(byte) => { - let byte: u64 = byte.into(); - byte.shl(8_u64 * byte_counter.into()) - }, - Option::None => { break; }, + + for byte_counter in 0 + ..last_input_num_bytes { + last_input_word += match self.at(full_u64_word_count * 8 + byte_counter.into()) { + Option::Some(byte) => { + let byte: u64 = byte.into(); + byte.shl(8_u64 * byte_counter.into()) + }, + Option::None => { break; }, + }; }; - byte_counter += 1; - }; (u64_words, last_input_word, last_input_num_bytes) } @@ -612,10 +602,8 @@ mod tests { let res = ByteArrayExTrait::from_bytes(arr.span()); // Ensure that the result is complete and keeps the same order - let mut i = 0; - while i != arr.len() { + for i in 0..arr.len() { assert(*arr[i] == res[i], 'byte mismatch'); - i += 1; }; } @@ -685,10 +673,8 @@ mod tests { let res = ByteArrayExTrait::from_bytes(arr.span()); // Ensure that the result is complete and keeps the same order - let mut i = 0; - while i != arr.len() { + for i in 0..arr.len() { assert(*arr[i] == res[i], 'byte mismatch'); - i += 1; }; } diff --git a/crates/utils/src/traits/eth_address.cairo b/crates/utils/src/traits/eth_address.cairo index c2f260716..9f0122b29 100644 --- a/crates/utils/src/traits/eth_address.cairo +++ b/crates/utils/src/traits/eth_address.cairo @@ -13,12 +13,11 @@ pub impl EthAddressExImpl of EthAddressExTrait { let bytes_used: u256 = 20; let value: u256 = self.into(); let mut bytes: Array = Default::default(); - let mut i = 0; - while i != bytes_used { - let val = value.shr(8 * (bytes_used - i - 1)); - bytes.append((val & 0xFF).try_into().unwrap()); - i += 1; - }; + for i in 0 + ..bytes_used { + let val = value.shr(8 * (bytes_used - i - 1)); + bytes.append((val & 0xFF).try_into().unwrap()); + }; bytes } @@ -40,13 +39,11 @@ pub impl EthAddressExImpl of EthAddressExTrait { } let offset: u32 = len - 1; let mut result: u256 = 0; - let mut i: u32 = 0; - while i != len { - let byte: u256 = (*input.at(i)).into(); - result += byte.shl((8 * (offset - i)).into()); - - i += 1; - }; + for i in 0 + ..len { + let byte: u256 = (*input.at(i)).into(); + result += byte.shl((8 * (offset - i)).into()); + }; result.try_into() } } diff --git a/crates/utils/src/traits/integer.cairo b/crates/utils/src/traits/integer.cairo index 9ee504f46..ebd00f99e 100644 --- a/crates/utils/src/traits/integer.cairo +++ b/crates/utils/src/traits/integer.cairo @@ -192,7 +192,7 @@ pub impl BitsUsedImpl< let bytes_used = self.bytes_used(); let last_byte = self.shr(eight * (bytes_used.into() - One::one())); - // safe unwrap since we know atmost 8 bits are used + // safe unwrap since we know at most 8 bits are used let bits_used: u8 = bits_used_internal::bits_used_in_byte(last_byte.try_into().unwrap()); bits_used.into() + 8 * (bytes_used - 1).into()