Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: buffer to vec of vec u64/felts for wasm/python #470

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,44 @@ pub fn bufferToVecOfVecU64(buffer: wasm_bindgen::Clamped<Vec<u8>>) -> wasm_bindg
wasm_bindgen::Clamped(serde_json::to_vec(&field_elements).unwrap())
}

/// Converts a buffer to vector of 4 u64s representing a fixed point field element
#[wasm_bindgen]
#[allow(non_snake_case)]
pub fn bufferToVecOfVecU64(buffer: wasm_bindgen::Clamped<Vec<u8>>) -> wasm_bindgen::Clamped<Vec<u8>> {
// Convert the buffer to a slice
let buffer: &[u8] = &buffer;

// Divide the buffer into chunks of 64 bytes
let chunks = buffer.chunks_exact(16);

// Get the remainder
let remainder = chunks.remainder();

// Add 0s to the remainder to make it 64 bytes
let mut remainder = remainder.to_vec();

// Collect chunks into a Vec<[u8; 16]>.
let mut chunks: Vec<[u8; 16]> = chunks.map(|slice| {
let array: [u8; 16] = slice.try_into().unwrap();
array
}).collect();

if remainder.len() != 0 {
remainder.resize(16, 0);
// Convert the Vec<u8> to [u8; 16]
let remainder_array: [u8; 16] = remainder.try_into().unwrap();
// append the remainder to the chunks
chunks.push(remainder_array);
}

// Convert each chunk to a field element
let field_elements: Vec<Fr> = chunks.iter().map(
|x| PrimeField::from_u128(u8_array_to_u128_le(*x))
).collect();

wasm_bindgen::Clamped(serde_json::to_vec(&field_elements).unwrap())
}

/// Generate a poseidon hash in browser. Input message
#[wasm_bindgen]
#[allow(non_snake_case)]
Expand Down
Loading