Skip to content

Commit

Permalink
Add const constructor to StarkFelt
Browse files Browse the repository at this point in the history
- Implement `from<128>` using const logic, so that it can be used as a
  const constructor.
- Also remove `StarkFelt::one()` which in favor of `StarkFelt::from_128(1_u128)`.
  • Loading branch information
giladchase committed Sep 6, 2023
1 parent f3f752d commit 2093bc1
Showing 1 changed file with 12 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,17 @@ impl StarkFelt {
])
}

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> {
// We use the fact that bytes[0] < 0x10 and encode the size of the felt in the 4 most
Expand Down Expand Up @@ -156,9 +167,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

0 comments on commit 2093bc1

Please sign in to comment.