From 18e8a77683c86e967484db117e7012d73a41b418 Mon Sep 17 00:00:00 2001 From: enitrat Date: Thu, 5 Sep 2024 11:50:49 +0200 Subject: [PATCH] dev: optimize FromBytes --- .tool-versions | 2 +- crates/utils/Scarb.toml | 6 ++++- crates/utils/src/helpers.cairo | 40 ++++++++++------------------------ 3 files changed, 18 insertions(+), 30 deletions(-) diff --git a/.tool-versions b/.tool-versions index f5e9048bd..30efda798 100644 --- a/.tool-versions +++ b/.tool-versions @@ -1,2 +1,2 @@ scarb 2.7.1 -starknet-foundry 0.28.0 +starknet-foundry 0.30.0 diff --git a/crates/utils/Scarb.toml b/crates/utils/Scarb.toml index ad856c94a..f637ecf2e 100644 --- a/crates/utils/Scarb.toml +++ b/crates/utils/Scarb.toml @@ -9,11 +9,15 @@ edition = "2023_10" evm = { path = "../evm" } alexandria_data_structures = { path = "../alexandria_data_structures" } +# For profiling +[cairo] +unstable-add-statements-functions-debug-info = true + [tool] fmt.workspace = true [dev-dependencies] -snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry.git", tag = "v0.28.0" } +snforge_std = { git = "https://github.com/foundry-rs/starknet-foundry.git", tag = "v0.30.0" } [scripts] test = "snforge test --max-n-steps 4294967295" diff --git a/crates/utils/src/helpers.cairo b/crates/utils/src/helpers.cairo index d2ce39238..2a7e19005 100644 --- a/crates/utils/src/helpers.cairo +++ b/crates/utils/src/helpers.cairo @@ -575,7 +575,7 @@ pub impl FromBytesImpl< +ByteSize, +BytesUsedTrait, +Into, - +Into, + +Into, +TryInto, +Copy, +Drop, @@ -585,47 +585,31 @@ pub impl FromBytesImpl< fn from_be_bytes(self: Span) -> Option { let byte_size = ByteSize::::byte_size(); - let len = self.len(); - if len == 0 { - return Option::Some(Zero::zero()); - } - if len > byte_size { + if self.len() != byte_size { return Option::None; } - let offset: u32 = len - 1; - let mut result: T = Zero::zero(); - let mut i: u32 = 0; - while i != len { - let byte: T = (*self.at(i)).into(); - // Safe unwrap, since offset - i is inbound in case of u8 { offset - i = 0 }, and - // TryInto, TryInto, TryInto, TryInto are safe - result += byte.shl((8 * (offset - i)).into()); - i += 1; + let mut result: T = Zero::zero(); + for byte in self { + let tmp = result * 256_u16.into(); + result = tmp + (*byte).into(); }; Option::Some(result) } fn from_le_bytes(self: Span) -> Option { let byte_size = ByteSize::::byte_size(); - let len = self.len(); - if len == 0 { - return Option::Some(Zero::zero()); - } - if len > byte_size { + if self.len() != byte_size { return Option::None; } let mut result: T = Zero::zero(); - let mut i: u32 = 0; - while i != len { - let byte: T = (*self.at(i)).into(); - // safe unwrap, as i is inbound in case of u8 { max value can be 8 * 1 = 8 }, and - // TryInto, TryInto, TryInto, TryInto are safe - result += byte.shl((8 * i).into()); - - i += 1; + let mut i = self.len(); + while i != 0 { + i -= 1; + let tmp = result * 256_u16.into(); + result = tmp + (*self[i]).into(); }; Option::Some(result) }