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) } }