|
1 | 1 | use crate::cyclic_group::IsGroup; |
2 | 2 | #[cfg(feature = "std")] |
3 | 3 | use crate::errors::ByteConversionError::{FromBEBytesError, FromLEBytesError}; |
| 4 | +use crate::errors::CreationError; |
4 | 5 | #[cfg(feature = "std")] |
5 | 6 | use crate::errors::DeserializationError; |
6 | 7 | use crate::field::element::FieldElement; |
@@ -84,6 +85,20 @@ impl<const MODULUS: u64> IsPrimeField for U64PrimeField<MODULUS> { |
84 | 85 | fn field_bit_size() -> usize { |
85 | 86 | ((MODULUS - 1).ilog2() + 1) as usize |
86 | 87 | } |
| 88 | + |
| 89 | + fn from_hex(hex_string: &str) -> Result<Self::BaseType, CreationError> { |
| 90 | + let mut hex_string = hex_string; |
| 91 | + // Remove 0x if it's on the string |
| 92 | + let mut char_iterator = hex_string.chars(); |
| 93 | + if hex_string.len() > 2 |
| 94 | + && char_iterator.next().unwrap() == '0' |
| 95 | + && char_iterator.next().unwrap() == 'x' |
| 96 | + { |
| 97 | + hex_string = &hex_string[2..]; |
| 98 | + } |
| 99 | + |
| 100 | + u64::from_str_radix(hex_string, 16).map_err(|_| CreationError::InvalidHexString) |
| 101 | + } |
87 | 102 | } |
88 | 103 |
|
89 | 104 | /// Represents an element in Fp. (E.g: 0, 1, 2 are the elements of F3) |
@@ -145,7 +160,18 @@ impl<const MODULUS: u64> Deserializable for FieldElement<U64PrimeField<MODULUS>> |
145 | 160 | mod tests { |
146 | 161 | use super::*; |
147 | 162 | const MODULUS: u64 = 13; |
148 | | - type FE = FieldElement<U64PrimeField<MODULUS>>; |
| 163 | + type F = U64PrimeField<MODULUS>; |
| 164 | + type FE = FieldElement<F>; |
| 165 | + |
| 166 | + #[test] |
| 167 | + fn from_hex_for_b_is_11() { |
| 168 | + assert_eq!(F::from_hex("B").unwrap(), 11); |
| 169 | + } |
| 170 | + |
| 171 | + #[test] |
| 172 | + fn from_hex_for_0x1_a_is_26() { |
| 173 | + assert_eq!(F::from_hex("0x1a").unwrap(), 26); |
| 174 | + } |
149 | 175 |
|
150 | 176 | #[test] |
151 | 177 | fn bit_size_of_mod_13_field_is_4() { |
|
0 commit comments