1
0
Fork 0
mirror of synced 2025-09-24 04:40:05 +00:00

Add usize implementations for Field (from, pow)

This commit is contained in:
Dennis Kuhnert 2017-02-19 16:18:16 +01:00
parent a8a67cd045
commit aef5a56d1f

View file

@ -21,13 +21,13 @@ pub trait Pow<RHS> {
fn pow(self, RHS) -> Self::Output; fn pow(self, RHS) -> Self::Output;
} }
pub trait Field : From<i32> + From<u32> + for<'a> From<&'a str> pub trait Field : From<i32> + From<u32> + From<usize> + for<'a> From<&'a str>
+ Zero + One + Clone + PartialEq + PartialOrd + Display + Debug + Zero + One + Clone + PartialEq + PartialOrd + Display + Debug
+ Add<Self, Output=Self> + for<'a> Add<&'a Self, Output=Self> + Add<Self, Output=Self> + for<'a> Add<&'a Self, Output=Self>
+ Sub<Self, Output=Self> + for<'a> Sub<&'a Self, Output=Self> + Sub<Self, Output=Self> + for<'a> Sub<&'a Self, Output=Self>
+ Mul<Self, Output=Self> + for<'a> Mul<&'a Self, Output=Self> + Mul<Self, Output=Self> + for<'a> Mul<&'a Self, Output=Self>
+ Div<Self, Output=Self> + for<'a> Div<&'a Self, Output=Self> + Div<Self, Output=Self> + for<'a> Div<&'a Self, Output=Self>
+ Pow<u32, Output=Self> + Pow<Self, Output=Self> + for<'a> Pow<&'a Self, Output=Self> + Pow<usize, Output=Self> + Pow<Self, Output=Self> + for<'a> Pow<&'a Self, Output=Self>
{ {
/// Returns the smallest value that can be represented by this field type. /// Returns the smallest value that can be represented by this field type.
fn min_value() -> Self; fn min_value() -> Self;
@ -85,6 +85,13 @@ impl From<u32> for FieldPrime {
} }
} }
impl From<usize> for FieldPrime {
fn from(num: usize) -> Self {
let x = ToBigInt::to_bigint(&num).unwrap();
FieldPrime { value: &x - x.div_floor(&*P) * &*P }
}
}
impl<'a> From<&'a str> for FieldPrime { impl<'a> From<&'a str> for FieldPrime {
fn from(s: &'a str) -> Self { fn from(s: &'a str) -> Self {
let x = BigInt::parse_bytes(s.as_bytes(), 10).unwrap(); let x = BigInt::parse_bytes(s.as_bytes(), 10).unwrap();
@ -174,10 +181,10 @@ impl<'a> Div<&'a FieldPrime> for FieldPrime {
} }
} }
impl Pow<u32> for FieldPrime { impl Pow<usize> for FieldPrime {
type Output = FieldPrime; type Output = FieldPrime;
fn pow(self, exp: u32) -> FieldPrime { fn pow(self, exp: usize) -> FieldPrime {
let mut res = FieldPrime::from(1); let mut res = FieldPrime::from(1);
for _ in 0..exp { for _ in 0..exp {
res = res * &self; res = res * &self;
@ -414,6 +421,14 @@ mod tests {
); );
} }
#[test]
fn pow_usize() {
assert_eq!(
"614787626176508399616".parse::<BigInt>().unwrap(),
(FieldPrime::from("54").pow(12)).value
);
}
#[test] #[test]
fn pow() { fn pow() {
assert_eq!( assert_eq!(