Skip to content

Commit

Permalink
Merge branch 'feat/cairo-2.5.0-while-loops' into cairo250-ontopof-muts
Browse files Browse the repository at this point in the history
  • Loading branch information
delaaxe committed Feb 1, 2024
2 parents 8febf47 + 7c93d4a commit 1898a08
Show file tree
Hide file tree
Showing 30 changed files with 243 additions and 383 deletions.
33 changes: 14 additions & 19 deletions src/ascii/src/integer.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,15 @@ impl ToAsciiArrayTraitImpl<
}

let mut num = self;
loop {
if num.is_zero() {
break;
}
let (quotient, remainder) = DivRem::div_rem(
num, TryInto::<felt252, T>::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::<felt252, T>::try_into(10).unwrap().try_into().expect('Division by 0')
);
new_arr.append(remainder.into() + 48);
num = quotient;
};
new_arr
}
}
Expand All @@ -71,12 +70,11 @@ impl SmallIntegerToAsciiTraitImpl<

let mut inverse_ascii_arr = self.to_inverse_ascii_array().span();
let mut ascii: felt252 = 0;
loop {
match inverse_ascii_arr.pop_back() {
Option::Some(val) => { ascii = ascii * 256 + *val; },
Option::None(_) => { break; },
while !inverse_ascii_arr
.is_empty() {
let val = *inverse_ascii_arr.pop_back().unwrap();
ascii = ascii * 256 + val;
};
};

ascii
}
Expand Down Expand Up @@ -153,10 +151,7 @@ impl U256ToAsciiArrayTraitImpl of ToAsciiArrayTrait<u256> {
return new_arr;
}
let mut num = self;
loop {
if num.is_zero() {
break;
}
while num != 0 {
let (quotient, remainder) = DivRem::div_rem(
num, 10_u256.try_into().expect('Division by 0')
);
Expand Down
31 changes: 10 additions & 21 deletions src/bytes/src/bytes.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,7 @@ impl BytesImpl of BytesTrait {
data_len += 1;
}

loop {
if data_len == 0 {
break;
};
while data_len != 0 {
data.append(0_u128);
data_len -= 1;
};
Expand Down Expand Up @@ -337,10 +334,7 @@ impl BytesImpl of BytesTrait {
// read full array element for sub_bytes
let mut offset = offset;
let mut sub_bytes_full_array_len = size / BYTES_PER_ELEMENT;
loop {
if sub_bytes_full_array_len == 0 {
break;
};
while sub_bytes_full_array_len != 0 {
let (new_offset, value) = self.read_u128(offset);
array.append(value);
offset = new_offset;
Expand Down Expand Up @@ -475,10 +469,7 @@ impl BytesImpl of BytesTrait {
// read full array element for other
let mut offset = 0;
let mut sub_bytes_full_array_len = *other.size / BYTES_PER_ELEMENT;
loop {
if sub_bytes_full_array_len == 0 {
break;
};
while sub_bytes_full_array_len != 0 {
let (new_offset, value) = other.read_u128(offset);
self.append_u128(value);
offset = new_offset;
Expand Down Expand Up @@ -514,15 +505,13 @@ impl BytesImpl of BytesTrait {
let mut hash_data: Array<u8> = array![];
let mut i: usize = 0;
let mut offset: usize = 0;
loop {
if i == self.size() {
break;
}
let (new_offset, hash_data_item) = self.read_u8(offset);
hash_data.append(hash_data_item);
offset = new_offset;
i += 1;
};
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 output: Array<u8> = sha256(hash_data);
u8_array_to_u256(output.span())
Expand Down
25 changes: 8 additions & 17 deletions src/data_structures/src/bit_array.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -279,12 +279,9 @@ impl BitArrayImpl of BitArrayTrait {
match self.pop_front() {
Option::Some(bit) => {
if bit {
result =
Option::Some(
(one_shift_left_bytes_felt252(byte_offset)
* shift_bit(bit_offset).into())
+ result.unwrap()
);
let shifted = one_shift_left_bytes_felt252(byte_offset);
let value = (shifted * shift_bit(bit_offset).into()) + result.unwrap();
result = Option::Some(value);
}
},
Option::None => {
Expand Down Expand Up @@ -340,25 +337,22 @@ impl BitArrayImpl of BitArrayTrait {
limb0: limb0.try_into().unwrap(),
limb1: limb1.try_into().unwrap(),
limb2: limb2.try_into().unwrap(),
limb3: limb3
limb3
}
} else if length > 128 {
let limb0 = self.read_word_le(128)?;
let limb1 = self.read_word_le(length - 128)?;
let limb2 = 0;
let limb3 = 0;
u512 {
limb0: limb0.try_into().unwrap(),
limb1: limb1.try_into().unwrap(),
limb2: limb2,
limb3: limb3
limb0: limb0.try_into().unwrap(), limb1: limb1.try_into().unwrap(), limb2, limb3
}
} else {
let limb0 = self.read_word_le(length)?;
let limb1 = 0;
let limb2 = 0;
let limb3 = 0;
u512 { limb0: limb0.try_into().unwrap(), limb1: limb1, limb2: limb2, limb3: limb3 }
u512 { limb0: limb0.try_into().unwrap(), limb1, limb2, limb3 }
}
)
}
Expand Down Expand Up @@ -460,8 +454,7 @@ impl BitArrayIndexView of IndexView<BitArray, usize, bool> {

impl BitArraySerde of Serde<BitArray> {
fn serialize(self: @BitArray, ref output: Array<felt252>) {
let length = self.len();
length.serialize(ref output);
self.len().serialize(ref output);
let bytes31_arr = self.data.span();
serialize_array_helper(bytes31_arr, ref output);
output.append(*self.current);
Expand All @@ -475,9 +468,7 @@ impl BitArraySerde of Serde<BitArray> {
ref serialized, array![], length_in_felts.into()
)?;
let current = *serialized.pop_front()?;
Option::Some(
BitArray { data: bytes31_arr, current: current, read_pos: 0, write_pos: length, }
)
Option::Some(BitArray { data: bytes31_arr, current, read_pos: 0, write_pos: length })
}
}

Expand Down
5 changes: 1 addition & 4 deletions src/encoding/src/reversible.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@ fn reversing_partial_result<
mut word: T, mut onto: T, size: usize, step: T
) -> (T, T) {
let mut i: usize = 0;
loop {
if i == size {
break;
}
while i != size {
let (new_word, remainder) = DivRem::div_rem(word, step.try_into().unwrap());
word = new_word;
onto *= step.into();
Expand Down
18 changes: 8 additions & 10 deletions src/linalg/src/dot.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,20 @@
/// * `xs` - The first sequence of len L.
/// * `ys` - The second sequence of len L.
/// # Returns
/// * `T` - The dot product.
/// * `sum` - The dot product.
fn dot<T, +Mul<T>, +AddEq<T>, +Zeroable<T>, +Copy<T>, +Drop<T>,>(
mut xs: Span<T>, mut ys: Span<T>
) -> T {
// [Check] Inputs
assert(xs.len() == ys.len(), 'Arrays must have the same len');

// [Compute] Dot product in a loop
let mut value = Zeroable::zero();
loop {
match xs.pop_front() {
Option::Some(x_value) => {
let y_value = ys.pop_front().unwrap();
value += *x_value * *y_value;
},
Option::None => { break value; },
let mut sum = Zeroable::zero();
while !xs
.is_empty() {
let x = *xs.pop_front().unwrap();
let y = *ys.pop_front().unwrap();
sum += x * y;
};
}
sum
}
20 changes: 8 additions & 12 deletions src/linalg/src/kron.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,16 @@ fn kron<T, +Mul<T>, +AddEq<T>, +Zeroable<T>, +Copy<T>, +Drop<T>,>(

// [Compute] Kronecker product in a loop
let mut array = array![];
loop {
match xs.pop_front() {
Option::Some(x_value) => {
let mut ys_clone = ys;
loop {
match ys_clone.pop_front() {
Option::Some(y_value) => { array.append(*x_value * *y_value); },
Option::None => { break; },
};
while !xs
.is_empty() {
let x = *xs.pop_front().unwrap();
let mut ys_copy = ys;
while !ys_copy
.is_empty() {
let y = *ys_copy.pop_front().unwrap();
array.append(x * y);
};
},
Option::None => { break; },
};
};

Result::Ok(array)
}
21 changes: 9 additions & 12 deletions src/linalg/src/norm.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,17 @@ fn norm<T, +Into<T, u128>, +Zeroable<T>, +Copy<T>>(
mut xs: Span<T>, ord: u128, iter: usize
) -> u128 {
let mut norm: u128 = 0;
loop {
match xs.pop_front() {
Option::Some(x_value) => {
if ord == 0 {
if (*x_value).is_non_zero() {
norm += 1;
}
} else {
norm += pow((*x_value).into(), ord);
while !xs
.is_empty() {
let x = xs.pop_front().unwrap();
if ord == 0 {
if (*x).is_non_zero() {
norm += 1;
}
},
Option::None => { break; },
} else {
norm += pow((*x).into(), ord);
}
};
};

if ord == 0 {
return norm;
Expand Down
4 changes: 2 additions & 2 deletions src/linalg/src/tests/dot_test.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use alexandria_linalg::dot::dot;
#[test]
#[available_gas(2000000)]
fn dot_product_test() {
let xs: Array<u64> = array![3, 5, 7];
let xs = array![3_u64, 5, 7];
let ys = array![11, 13, 17];
assert(dot(xs.span(), ys.span()) == 217, 'invalid dot product');
}
Expand All @@ -12,7 +12,7 @@ fn dot_product_test() {
#[should_panic(expected: ('Arrays must have the same len',))]
#[available_gas(2000000)]
fn dot_product_test_check_len() {
let xs: Array<u64> = array![1];
let xs = array![1_u64];
let ys = array![];
dot(xs.span(), ys.span());
}
4 changes: 2 additions & 2 deletions src/linalg/src/tests/kron_test.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use alexandria_linalg::kron::{kron, KronError};
#[test]
#[available_gas(2000000)]
fn kron_product_test() {
let xs: Array<u64> = array![1, 10, 100];
let xs = array![1_u64, 10, 100];
let ys = array![5, 6, 7];
let zs = kron(xs.span(), ys.span()).unwrap();
assert(*zs[0] == 5, 'wrong value at index 0');
Expand All @@ -20,7 +20,7 @@ fn kron_product_test() {
#[test]
#[available_gas(2000000)]
fn kron_product_test_check_len() {
let xs: Array<u64> = array![1];
let xs = array![1_u64];
let ys = array![];
assert(
kron(xs.span(), ys.span()) == Result::Err(KronError::UnequalLength),
Expand Down
8 changes: 4 additions & 4 deletions src/linalg/src/tests/norm_test.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,27 @@ use alexandria_linalg::norm::norm;
#[test]
#[available_gas(2000000)]
fn norm_test_1() {
let array: Array<u128> = array![3, 4];
let array = array![3_u128, 4];
assert(norm(array.span(), 2, 10) == 5, 'invalid l2 norm');
}

#[test]
#[available_gas(2000000)]
fn norm_test_2() {
let array: Array<u128> = array![3, 4];
let array = array![3_u128, 4];
assert(norm(array.span(), 1, 10) == 7, 'invalid l1 norm');
}

#[test]
#[available_gas(2000000)]
fn norm_test_3() {
let array: Array<u128> = array![3, 4];
let array = array![3_u128, 4];
assert(norm(array.span(), 0, 10) == 2, 'invalid l1 norm');
}

#[test]
#[available_gas(2000000)]
fn norm_test_into() {
let array: Array<u32> = array![3, 4];
let array = array![3_u32, 4];
assert(norm(array.span(), 2, 10) == 5, 'invalid l2 norm');
}
9 changes: 3 additions & 6 deletions src/math/src/fast_root.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,7 @@ fn fast_nr_optimize(x: u128, r: u128, iter: usize) -> u128 {
let mut x_optim = round_div(x, r);
let mut n_iter = 0;

loop {
if n_iter == iter {
break;
}
while n_iter != iter {
let x_r_m1 = pow(x_optim, r - 1);
x_optim = round_div(((r - 1) * x_optim + round_div(x, x_r_m1)), r);
n_iter += 1;
Expand All @@ -40,7 +37,7 @@ fn fast_nr_optimize(x: u128, r: u128, iter: usize) -> u128 {
/// # Returns
/// * ` u128 ` - The sqrt of x with rounding (e.g., sqrt(5) = 2.24 -> 2, sqrt(7) = 2.65 -> 3)
fn fast_sqrt(x: u128, iter: usize) -> u128 {
return fast_nr_optimize(x, 2, iter);
fast_nr_optimize(x, 2, iter)
}

/// Calculate the cubic root of x
Expand All @@ -50,7 +47,7 @@ fn fast_sqrt(x: u128, iter: usize) -> u128 {
/// # Returns
/// * ` u128 ` - The cubic root of x with rounding (e.g., cbrt(4) = 1.59 -> 2, cbrt(5) = 1.71 -> 2)
fn fast_cbrt(x: u128, iter: usize) -> u128 {
return fast_nr_optimize(x, 3, iter);
fast_nr_optimize(x, 3, iter)
}

/// Calculate the division of a by b with rounding
Expand Down
Loading

0 comments on commit 1898a08

Please sign in to comment.