Skip to content

Commit 5c330ad

Browse files
committed
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)`.
1 parent 9b4c7e3 commit 5c330ad

File tree

1 file changed

+16
-27
lines changed

1 file changed

+16
-27
lines changed

src/hash.rs

Lines changed: 16 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -58,36 +58,27 @@ impl StarkFelt {
5858
}
5959

6060
/// [StarkFelt] constant that's equal to 0.
61-
pub const ZERO: Self = {
62-
Self([
63-
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
64-
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
65-
])
66-
};
61+
pub const ZERO: Self = { Self::from_u128(0_u128) };
6762

6863
/// [StarkFelt] constant that's equal to 1.
69-
pub const ONE: Self = {
70-
Self([
71-
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
72-
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1,
73-
])
74-
};
64+
pub const ONE: Self = { Self::from_u128(1_u128) };
7565

7666
/// [StarkFelt] constant that's equal to 2.
77-
pub const TWO: Self = {
78-
Self([
79-
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
80-
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2,
81-
])
82-
};
67+
pub const TWO: Self = { Self::from_u128(2_u128) };
8368

8469
/// [StarkFelt] constant that's equal to 3.
85-
pub const THREE: Self = {
86-
Self([
87-
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
88-
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3,
89-
])
90-
};
70+
pub const THREE: Self = { Self::from_u128(3_u128) };
71+
72+
pub const fn from_u128(val: u128) -> Self {
73+
let mut bytes = [0u8; 32];
74+
let val_bytes = val.to_be_bytes();
75+
let mut index = 16;
76+
while index < 32 {
77+
bytes[index] = val_bytes[index - 16];
78+
index += 1;
79+
}
80+
Self(bytes)
81+
}
9182

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

180171
impl From<u128> for StarkFelt {
181172
fn from(val: u128) -> Self {
182-
let mut bytes = [0u8; 32];
183-
bytes[16..32].copy_from_slice(&val.to_be_bytes());
184-
Self(bytes)
173+
Self::from_u128(val)
185174
}
186175
}
187176

0 commit comments

Comments
 (0)