1#![deny(rustdoc::broken_intra_doc_links)]
4#![deny(missing_debug_implementations)]
5#![deny(missing_docs)]
6
7use ff::{Field, PrimeField};
8
9use num_bigint::{BigInt, BigUint};
10use num_traits::{Num as _, Signed as _};
11
12use crate::error::Error;
13
14pub mod cells;
15pub mod circuit;
16pub mod error;
17pub mod macros;
18
19pub use haloumi_ir as ir;
20
21pub trait Halo2Types<F: Field> {
26 type InstanceCol: std::fmt::Debug + Copy + Clone;
28 type AdviceCol: std::fmt::Debug + Copy + Clone;
30 type Cell: std::fmt::Debug + Copy + Clone;
32 type AssignedCell<V>;
34 type Region<'a>;
36 type Error: Into<crate::error::Error> + From<crate::error::Error>;
38 type RegionIndex: std::hash::Hash + Copy + Eq;
40 type Expression;
42 type Rational;
44}
45
46pub fn parse_field<F: PrimeField>(s: &str) -> Result<F, Error> {
48 if s.is_empty() {
49 return Err(Error::FieldParsingError);
50 }
51 let ten = F::from(10);
52 s.chars()
53 .map(|c| c.to_digit(10).ok_or(Error::FieldParsingError))
54 .map(|r| r.map(u64::from))
55 .map(|r| r.map(F::from))
56 .fold(Ok(F::ZERO), |acc, c| Ok(acc? * ten + c?))
57}
58
59fn modulus<F: PrimeField>() -> BigUint {
61 BigUint::from_str_radix(&F::MODULUS[2..], 16).unwrap()
62}
63
64fn modulus_signed<F: PrimeField>() -> BigInt {
66 BigInt::from_str_radix(&F::MODULUS[2..], 16).unwrap()
67}
68
69pub fn big_to_fe<F: PrimeField>(e: BigUint) -> F {
71 let modulus = modulus::<F>();
72 let e = e % modulus;
73 F::from_str_vartime(&e.to_str_radix(10)[..]).unwrap()
74}
75
76pub fn sbig_to_fe<F: PrimeField>(mut e: BigInt) -> F {
79 let modulus = modulus_signed::<F>();
80 e = (e % modulus).abs();
81 F::from_str_vartime(&e.to_str_radix(10)[..]).unwrap()
82}
83
84pub fn fe_to_big<F: PrimeField>(fe: F) -> BigUint {
86 BigUint::from_bytes_le(fe.to_repr().as_ref())
87}
88
89#[macro_export]
92macro_rules! cell_to_expr {
93 ($x:expr, $F:ty) => {{
94 let c = $x.cell();
95 i32::try_from(c.row_offset)
96 .map(midnight_proofs::poly::Rotation)
97 .map(|r| c.column.query_cell::<$F>(r))
98 .map_err($crate::error::Error::from)
99 }};
100}