Skip to content

Commit 7888092

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 f3f752d commit 7888092

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

src/hash.rs

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,18 @@ impl StarkFelt {
6060
}
6161

6262
pub const fn one() -> Self {
63-
Self([
64-
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0,
65-
0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1,
66-
])
63+
Self::from_u128(1_u128)
64+
}
65+
66+
pub const fn from_u128(val: u128) -> Self {
67+
let mut bytes = [0u8; 32];
68+
let val_bytes = val.to_be_bytes();
69+
let mut index = 16;
70+
while index < 32 {
71+
bytes[index] = val_bytes[index - 16];
72+
index += 1;
73+
}
74+
Self(bytes)
6775
}
6876

6977
/// Storage efficient serialization for field elements.
@@ -156,9 +164,7 @@ impl TryFrom<&str> for StarkFelt {
156164

157165
impl From<u128> for StarkFelt {
158166
fn from(val: u128) -> Self {
159-
let mut bytes = [0u8; 32];
160-
bytes[16..32].copy_from_slice(&val.to_be_bytes());
161-
Self(bytes)
167+
Self::from_u128(val)
162168
}
163169
}
164170

0 commit comments

Comments
 (0)