turshi/
helper.rs

1//! This module includes some field helpers that are useful for Cairo
2
3use ark_ff::Field;
4use o1_utils::FieldHelpers;
5
6//(TODO move to utils inside FieldHelpers)
7
8/// Field element helpers for Cairo
9pub trait CairoFieldHelpers<F> {
10    /// Return field element as byte, if it fits. Otherwise returns least significant byte
11    fn lsb(&self) -> u8;
12
13    /// Return `pos`-th 16-bit chunk as another field element
14    fn u16_chunk(&self, pos: usize) -> F;
15
16    /// Return first 64 bits of the field element
17    fn to_u64(&self) -> u64;
18
19    /// Return a field element in hexadecimal in big endian
20    fn to_hex_be(&self) -> String;
21}
22
23impl<F: Field> CairoFieldHelpers<F> for F {
24    fn lsb(&self) -> u8 {
25        self.to_bytes()[0]
26    }
27
28    fn u16_chunk(&self, pos: usize) -> F {
29        let bytes = self.to_bytes();
30        let chunk = u16::from(bytes[2 * pos]) + u16::from(bytes[2 * pos + 1]) * 2u16.pow(8);
31        F::from(chunk)
32    }
33
34    fn to_u64(&self) -> u64 {
35        let bytes = self.to_bytes();
36        let mut acc: u64 = 0;
37        for i in 0..8 {
38            acc += 2u64.pow(i * 8) * (bytes[i as usize] as u64);
39        }
40        acc
41    }
42
43    fn to_hex_be(&self) -> String {
44        let mut bytes = self.to_bytes();
45        bytes.reverse();
46        hex::encode(bytes)
47    }
48}