From 5c330ad7defe0b8a56635e9660f580bee34ac6e2 Mon Sep 17 00:00:00 2001 From: Gilad Chase Date: Tue, 5 Sep 2023 17:39:59 +0300 Subject: [PATCH] Add const constructor to `StarkFelt` - 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)`. --- src/hash.rs | 43 ++++++++++++++++--------------------------- 1 file changed, 16 insertions(+), 27 deletions(-) diff --git a/src/hash.rs b/src/hash.rs index 24c810a6..ee48b358 100644 --- a/src/hash.rs +++ b/src/hash.rs @@ -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> { @@ -179,9 +170,7 @@ impl TryFrom<&str> for StarkFelt { impl From 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) } }