crypto_bigint/traits.rs
1//! Traits provided by this crate
2
3use crate::Limb;
4
5/// Compute `self + rhs mod p`.
6pub trait AddMod<Rhs = Self> {
7 /// Output type.
8 type Output;
9
10 /// Compute `self + rhs mod p`.
11 ///
12 /// Assumes `self` and `rhs` are `< p`.
13 fn add_mod(&self, rhs: &Rhs, p: &Self) -> Self::Output;
14}
15
16/// Compute `self - rhs mod p`.
17pub trait SubMod<Rhs = Self> {
18 /// Output type.
19 type Output;
20
21 /// Compute `self - rhs mod p`.
22 ///
23 /// Assumes `self` and `rhs` are `< p`.
24 fn sub_mod(&self, rhs: &Rhs, p: &Self) -> Self::Output;
25}
26
27/// Compute `-self mod p`.
28pub trait NegMod {
29 /// Output type.
30 type Output;
31
32 /// Compute `-self mod p`.
33 #[must_use]
34 fn neg_mod(&self, p: &Self) -> Self::Output;
35}
36
37/// Compute `self * rhs mod p`.
38///
39/// Requires `p_inv = -(p^{-1} mod 2^{BITS}) mod 2^{BITS}` to be provided for efficiency.
40pub trait MulMod<Rhs = Self> {
41 /// Output type.
42 type Output;
43
44 /// Compute `self * rhs mod p`.
45 ///
46 /// Requires `p_inv = -(p^{-1} mod 2^{BITS}) mod 2^{BITS}` to be provided for efficiency.
47 fn mul_mod(&self, rhs: &Rhs, p: &Self, p_inv: Limb) -> Self::Output;
48}
49
50/// Concatenate two numbers into a "wide" twice-width value, using the `rhs`
51/// value as the least significant value.
52pub trait Concat<Rhs = Self> {
53 /// Concatenated output: twice the width of `Self`.
54 type Output;
55
56 /// Concate the two values, with `self` as most significant and `rhs` as
57 /// the least significant.
58 fn concat(&self, rhs: &Self) -> Self::Output;
59}
60
61/// Split a number in half, returning the most significant half followed by
62/// the least significant.
63pub trait Split<Rhs = Self> {
64 /// Split output: high/low components of the value.
65 type Output;
66
67 /// Split this number in half, returning its high and low components
68 /// respectively.
69 fn split(&self) -> (Self::Output, Self::Output);
70}
71
72/// Encoding support.
73pub trait Encoding: Sized {
74 /// Size of this integer in bits.
75 const BIT_SIZE: usize;
76
77 /// Size of this integer in bytes.
78 const BYTE_SIZE: usize;
79
80 /// Byte array representation.
81 type Repr: Copy + Clone + AsRef<[u8]> + AsMut<[u8]> + Sized;
82
83 /// Decode from big endian bytes.
84 fn from_be_bytes(bytes: Self::Repr) -> Self;
85
86 /// Decode from little endian bytes.
87 fn from_le_bytes(bytes: Self::Repr) -> Self;
88
89 /// Encode to big endian bytes.
90 fn to_be_bytes(&self) -> Self::Repr;
91
92 /// Encode to little endian bytes.
93 fn to_le_bytes(&self) -> Self::Repr;
94}