jf_relation/gadgets/
utils.rs

1// Copyright (c) 2022 Espresso Systems (espressosys.com)
2// This file is part of the Jellyfish library.
3
4// You should have received a copy of the MIT License
5// along with the Jellyfish library. If not, see <https://mit-license.org/>.
6
7//! Helper functions for circuit gadgets implementation
8
9use crate::CircuitError;
10use ark_std::{cmp::Ordering, string::ToString};
11
12// helper function to find the next multiple of `divisor` for `current` value
13pub(crate) fn next_multiple(current: usize, divisor: usize) -> Result<usize, CircuitError> {
14    if divisor == 0 || divisor == 1 {
15        return Err(CircuitError::InternalError(
16            "can only be a multiple of divisor >= 2".to_string(),
17        ));
18    }
19    match current.cmp(&divisor) {
20        Ordering::Equal => Ok(current),
21        Ordering::Less => Ok(divisor),
22        Ordering::Greater => Ok((current / divisor + 1) * divisor),
23    }
24}
25
26#[cfg(test)]
27mod test {
28    use super::next_multiple;
29    use crate::CircuitError;
30
31    #[test]
32    fn test_helper_next_multiple() -> Result<(), CircuitError> {
33        assert!(next_multiple(5, 0).is_err());
34        assert!(next_multiple(5, 1).is_err());
35
36        assert_eq!(next_multiple(5, 2)?, 6);
37        assert_eq!(next_multiple(5, 3)?, 6);
38        assert_eq!(next_multiple(5, 4)?, 8);
39        assert_eq!(next_multiple(5, 5)?, 5);
40        assert_eq!(next_multiple(5, 11)?, 11);
41        Ok(())
42    }
43}