From aeb9a0d72c489b5b8542f9bcb3b67d98c50ae26f Mon Sep 17 00:00:00 2001 From: enitrat Date: Wed, 2 Oct 2024 18:46:56 +0200 Subject: [PATCH] opti from_le_bytes --- crates/utils/src/traits/bytes.cairo | 30 +++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/crates/utils/src/traits/bytes.cairo b/crates/utils/src/traits/bytes.cairo index 40b2637c..33e68e7e 100644 --- a/crates/utils/src/traits/bytes.cairo +++ b/crates/utils/src/traits/bytes.cairo @@ -363,7 +363,7 @@ pub impl FromBytesImpl< Option::Some(result) } - fn from_le_bytes(self: Span) -> Option { + fn from_le_bytes(mut self: Span) -> Option { let byte_size = ByteSize::::byte_size(); if self.len() != byte_size { @@ -371,16 +371,19 @@ pub impl FromBytesImpl< } let mut result: T = Zero::zero(); - let mut i = self.len(); - while i != 0 { - i -= 1; - let tmp = result * 256_u16.into(); - result = tmp + (*self[i]).into(); + loop { + match self.pop_back() { + Option::None => { break; }, + Option::Some(byte) => { + let tmp = result * 256_u16.into(); + result = tmp + (*byte).into(); + } + }; }; Option::Some(result) } - fn from_le_bytes_partial(self: Span) -> Option { + fn from_le_bytes_partial(mut self: Span) -> Option { let byte_size = ByteSize::::byte_size(); if self.len() > byte_size { @@ -388,11 +391,14 @@ pub impl FromBytesImpl< } let mut result: T = Zero::zero(); - let mut i = self.len(); - while i != 0 { - i -= 1; - let tmp = result * 256_u16.into(); - result = tmp + (*self[i]).into(); + loop { + match self.pop_back() { + Option::None => { break; }, + Option::Some(byte) => { + let tmp = result * 256_u16.into(); + result = tmp + (*byte).into(); + } + }; }; Option::Some(result) }