From 10a5b78f35a017b92a3f24e1d9c88a16b3f9ecac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timoth=C3=A9e=20Delabrouille?= <34384633+tdelabro@users.noreply.github.com> Date: Thu, 11 Jan 2024 05:39:11 +0100 Subject: [PATCH] feat: impl From for StarkFelt (#164) * feat: impl From for StarkFelt * add safety comment on new_unchecked * improve docstrings --- .gitignore | 1 + src/core.rs | 9 +++++++++ src/hash.rs | 18 ++++++++++++++++++ 3 files changed, 28 insertions(+) diff --git a/.gitignore b/.gitignore index 8e1ad418..d68be5fc 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ /logs /target /Cargo.lock +*.DS_Store diff --git a/src/core.rs b/src/core.rs index 20b37f13..561a3f54 100644 --- a/src/core.rs +++ b/src/core.rs @@ -264,6 +264,15 @@ impl TryFrom for EthAddress { } } +impl From for StarkFelt { + fn from(value: EthAddress) -> Self { + let mut bytes = [0u8; 32]; + // Padding H160 with zeros to 32 bytes (big endian) + bytes[12..32].copy_from_slice(value.0.as_bytes()); + StarkFelt::new_unchecked(bytes) + } +} + impl TryFrom> for EthAddress { type Error = StarknetApiError; fn try_from(val: PrefixedBytesAsHex<20_usize>) -> Result { diff --git a/src/hash.rs b/src/hash.rs index acbb1838..e9ab99d2 100644 --- a/src/hash.rs +++ b/src/hash.rs @@ -69,6 +69,24 @@ impl StarkFelt { Err(StarknetApiError::OutOfRange { string: hex_str_from_bytes::<32, true>(bytes) }) } + /// Returns a new *unchecked* [`StarkFelt`] + /// + /// # Safety + /// + /// To avoid undefined behavior, refer to [`StarkFelt`] struct's docstring + /// for the required constraints on the `bytes` argument, or use [`StarkFelt::new`] instead of + /// this method. + /// + /// # Usage + /// + /// Most of the time you should use `new` instead, but it comes in handy for a few cases: + /// - creating instances of `StarkFelt` at compile time + /// - implementing `From for StarkFelt` for types that have a smaller binary representation + /// than `StarkFelt` + pub const fn new_unchecked(bytes: [u8; 32]) -> StarkFelt { + Self(bytes) + } + /// [StarkFelt] constant that's equal to 0. pub const ZERO: Self = { Self::from_u128(0_u128) };