risc0_zkp/core/
mod.rs

1// Copyright 2024 RISC Zero, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Core module used to implement a zk-STARK prover and verifier.
16
17#![deny(missing_docs)]
18
19extern crate alloc;
20
21pub mod digest;
22pub mod hash;
23pub mod ntt;
24pub mod poly;
25
26use rand_core::RngCore;
27
28/// For x = (1 << po2), given x, find po2.
29/// # Example
30/// ```rust
31/// # use risc0_zkp::core::to_po2;
32/// #
33/// assert_eq!(to_po2(7), 2);
34/// assert_eq!(to_po2(10), 3);
35/// ```
36pub fn to_po2(x: usize) -> usize {
37    (31 - (x as u32).leading_zeros()) as usize
38}
39
40/// Compute `ceil(log_2(value))`
41///
42/// Find the smallest `result` such that, for the provided value,
43/// `2^result >= value`.
44/// # Example
45/// ```rust
46/// # use risc0_zkp::core::log2_ceil;
47/// #
48/// assert_eq!(log2_ceil(8), 3); // 2^3 = 8
49/// assert_eq!(log2_ceil(32), 5); // 2^5 = 32
50/// ```
51#[inline]
52pub const fn log2_ceil(value: usize) -> usize {
53    let mut result = 0;
54    while (1 << result) < value {
55        result += 1;
56    }
57    result
58}
59
60/// Generic trait for generating random values.
61pub trait Random {
62    /// Generate a uniform random value.
63    fn random<R: RngCore>(rng: &mut R) -> Self;
64}
65
66impl Random for u32 {
67    /// Return a random u32 value.
68    fn random<R: RngCore>(rng: &mut R) -> Self {
69        rng.next_u32()
70    }
71}