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

Add const constructor to StarkFelt #128

Merged
merged 1 commit into from
Sep 14, 2023
Merged
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
43 changes: 16 additions & 27 deletions src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,36 +58,27 @@ impl StarkFelt {
}

/// [StarkFelt] constant that's equal to 0.
pub const ZERO: Self = {
Self([
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
])
};
pub const ZERO: Self = { Self::from_u128(0_u128) };

/// [StarkFelt] constant that's equal to 1.
pub const ONE: Self = {
Self([
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1,
])
};
pub const ONE: Self = { Self::from_u128(1_u128) };

/// [StarkFelt] constant that's equal to 2.
pub const TWO: Self = {
Self([
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2,
])
};
pub const TWO: Self = { Self::from_u128(2_u128) };

/// [StarkFelt] constant that's equal to 3.
pub const THREE: Self = {
Self([
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3,
])
};
pub const THREE: Self = { Self::from_u128(3_u128) };

pub const fn from_u128(val: u128) -> Self {
let mut bytes = [0u8; 32];
let val_bytes = val.to_be_bytes();
let mut index = 16;
while index < 32 {
bytes[index] = val_bytes[index - 16];
index += 1;
}
Self(bytes)
}

/// Storage efficient serialization for field elements.
pub fn serialize(&self, res: &mut impl std::io::Write) -> Result<(), Error> {
Expand Down Expand Up @@ -179,9 +170,7 @@ impl TryFrom<&str> for StarkFelt {

impl From<u128> for StarkFelt {
fn from(val: u128) -> Self {
let mut bytes = [0u8; 32];
bytes[16..32].copy_from_slice(&val.to_be_bytes());
Self(bytes)
Self::from_u128(val)
}
}

Expand Down
Loading