Skip to content

Commit

Permalink
feat: span pad end zeroes (#277)
Browse files Browse the repository at this point in the history
* feat: span pad end zeroes

* rename fn

* docs: add cairodoc
  • Loading branch information
enitrat authored Sep 7, 2023
1 parent 266086c commit 39e09d9
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
38 changes: 38 additions & 0 deletions crates/utils/src/helpers.cairo
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,44 @@ impl ArrayExtension of ArrayExtensionTrait {
}
}

#[generate_trait]
impl SpanExtension of SpanExtensionTrait {
/// Pads a span of bytes with zeroes on the right.
///
/// It creates a new `Array<u8>` instance and clones each element of the input span to it,
/// and then adds the required amount of zeroes.
///
/// # Arguments
///
/// * `self` - The `Span<u8>` instance to pad with zeroes.
/// * `n_zeroes` - The number of zeroes to add to the right of the span.
///
/// # Returns
///
/// A new `Span<u8>` instance which has a length equal to the length of the input
/// span plus the number of zeroes specified.
fn pad_right(self: Span<u8>, n_zeroes: usize) -> Span<u8> {
let mut res: Array<u8> = array![];
let mut i = 0;
loop {
if i == self.len() {
break;
}
res.append(*self[i]);
i += 1;
};
let mut i = 0;
loop {
if i == n_zeroes {
break ();
}
res.append(0);
i += 1;
};
res.span()
}
}

// Raise a number to a power.
fn pow(base: felt252, exp: felt252) -> felt252 {
if exp == 0 {
Expand Down
8 changes: 8 additions & 0 deletions crates/utils/src/tests/test_helpers.cairo
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use utils::helpers;
use utils::helpers::{SpanExtension, SpanExtensionTrait};
use array::{ArrayTrait, SpanTrait};
use debug::PrintTrait;

Expand Down Expand Up @@ -155,3 +156,10 @@ fn test_split_word() {
};
}

#[test]
#[available_gas(2000000000)]
fn test_clone_pad_zeroes() {
let mut original: Span<u8> = array![1, 2, 3, 4].span();
let res = original.pad_right(3);
assert(res == array![1, 2, 3, 4, 0, 0, 0].span(), 'padding mismatch');
}

0 comments on commit 39e09d9

Please sign in to comment.