diff --git a/crates/starknet-types-core/Cargo.toml b/crates/starknet-types-core/Cargo.toml index a280e72..09a1903 100644 --- a/crates/starknet-types-core/Cargo.toml +++ b/crates/starknet-types-core/Cargo.toml @@ -29,7 +29,7 @@ lazy_static = { version = "1.4.0", default-features = false, features = [ default = ["std", "serde", "curve"] curve = [] hash = ["dep:lambdaworks-crypto"] -std = [] +std = ["alloc"] alloc = ["serde?/alloc"] arbitrary = ["std", "dep:arbitrary"] diff --git a/crates/starknet-types-core/src/felt.rs b/crates/starknet-types-core/src/felt.rs index 6bbe358..f8a4a38 100644 --- a/crates/starknet-types-core/src/felt.rs +++ b/crates/starknet-types-core/src/felt.rs @@ -210,6 +210,13 @@ impl Felt { BitArray::new(limbs) } + /// Helper to produce a hexadecimal formatted string. + /// Equivalent to calling `format!("{self:#x}")`. + #[cfg(feature = "alloc")] + pub fn to_hex_string(&self) -> alloc::string::String { + alloc::format!("{self:#x}") + } + /// Converts to little-endian bit representation. /// This is as performant as [to_bits_be](Felt::to_bits_be) pub fn to_bits_le(&self) -> BitArray { @@ -465,6 +472,7 @@ impl From for Felt { } } } + impl From<&BigInt> for Felt { fn from(bigint: &BigInt) -> Felt { let (sign, bytes) = bigint.mod_floor(&CAIRO_PRIME_BIGINT).to_bytes_le(); @@ -1068,6 +1076,12 @@ mod test { prop_assert_eq!(x, y); } + #[test] + #[cfg(feature = "alloc")] + fn to_hex_string_is_same_as_format(ref x in any::()) { + prop_assert_eq!(alloc::format!("{x:#x}"), x.to_hex_string()); + } + #[test] fn from_bytes_le_slice_works_for_all_lengths(x in 0..1000usize) { let bytes: [u8; 1000] = core::array::from_fn(|i| i as u8); @@ -1710,6 +1724,7 @@ mod test { ); } } + #[test] fn bool_into_felt() { let zero: Felt = false.into();