Skip to content

Commit 2093bc1

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 2093bc1

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

src/hash.rs

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,17 @@ impl StarkFelt {
6666
])
6767
}
6868

69+
pub const fn from_u128(val: u128) -> Self {
70+
let mut bytes = [0u8; 32];
71+
let val_bytes = val.to_be_bytes();
72+
let mut index = 16;
73+
while index < 32 {
74+
bytes[index] = val_bytes[index - 16];
75+
index += 1;
76+
}
77+
Self(bytes)
78+
}
79+
6980
/// Storage efficient serialization for field elements.
7081
pub fn serialize(&self, res: &mut impl std::io::Write) -> Result<(), Error> {
7182
// We use the fact that bytes[0] < 0x10 and encode the size of the felt in the 4 most
@@ -156,9 +167,7 @@ impl TryFrom<&str> for StarkFelt {
156167

157168
impl From<u128> for StarkFelt {
158169
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)
170+
Self::from_u128(val)
162171
}
163172
}
164173

0 commit comments

Comments
 (0)