rust_bigint/
traits.rs

1//! Traits to define common functionality across BigInt implementations. This is based on MIT/Apache-licensed
2/// work by [KZen](https://github.com/KZen-networks/curv/blob/master/src/arithmetic/traits.rs)
3
4use super::BigInt;
5use super::HexError;
6use std::marker::Sized;
7
8/// A zeroize trait common to BigInts
9pub trait ZeroizeBN {
10    fn zeroize_bn(&mut self);
11}
12
13/// Convert BigInt to and from various formats
14pub trait Converter {
15    /// Convert BigInt to `Vec<u8>`
16    fn to_vec(n: &Self) -> Vec<u8>;
17    /// Convert BigInt to a hex string
18    fn to_hex(&self) -> String;
19    /// Create a BigInt from a hex String
20    fn from_hex(n: &str) -> Result<BigInt, HexError>;
21    /// Create a BigInt from bytes
22    fn from_bytes(bytes: &[u8]) -> Self;
23    /// Convert a BigInt to bytes
24    fn to_bytes(&self) -> Vec<u8>;
25}
26
27/// Mod operations for BigInt
28pub trait Modulo {
29    fn mod_pow(base: &Self, exponent: &Self, modulus: &Self) -> Self;
30    fn mod_mul(a: &Self, b: &Self, modulus: &Self) -> Self;
31    fn mod_sub(a: &Self, b: &Self, modulus: &Self) -> Self;
32    fn mod_add(a: &Self, b: &Self, modulus: &Self) -> Self;
33    fn mod_inv(a: &Self, modulus: &Self) -> Self;
34}
35
36/// Sampling trait (e.g., for rejection sampling)
37pub trait Samplable {
38    fn sample_below(upper: &Self) -> Self;
39    fn sample_range(lower: &Self, upper: &Self) -> Self;
40    fn strict_sample_range(lower: &Self, upper: &Self) -> Self;
41    fn sample(bitsize: usize) -> Self;
42    fn strict_sample(bit_size: usize) -> Self;
43}
44
45/// Numerical tests for a BigInt
46pub trait NumberTests {
47    /// Is a BigInt equal to zero
48    fn is_zero(_: &Self) -> bool;
49    /// Is a BigInt even
50    fn is_even(_: &Self) -> bool;
51    /// Is a BitInt negative
52    fn is_negative(_: &Self) -> bool;
53    /// How many bits in a BigInt
54    fn bits(_: &Self) -> usize;
55}
56
57/// Trait for the extended eucledian algorithm
58pub trait EGCD
59where
60    Self: Sized,
61{
62    /// The extended eucledian algorithm
63    fn egcd(a: &Self, b: &Self) -> (Self, Self, Self);
64}
65
66/// Allow bit manipulation across BigInts
67pub trait BitManipulation {
68    /// Set a given bit
69    fn set_bit(self: &mut Self, bit: usize, bit_val: bool);
70    /// Test value of given bit
71    fn test_bit(self: &Self, bit: usize) -> bool;
72}
73
74/// Trait to allow other BigInt conversion (e.g., from u64)
75pub trait ConvertFrom<T> {
76    fn _from(_: &T) -> Self;
77}