diff --git a/bindings/rust/src/ethereum_kzg_settings/mod.rs b/bindings/rust/src/ethereum_kzg_settings/mod.rs index 18069d075..8961ceb95 100644 --- a/bindings/rust/src/ethereum_kzg_settings/mod.rs +++ b/bindings/rust/src/ethereum_kzg_settings/mod.rs @@ -1,6 +1,13 @@ use crate::KzgSettings; -use alloc::{boxed::Box, sync::Arc}; -use once_cell::race::OnceBox; +use alloc::sync::Arc; + +#[cfg(not(feature = "std"))] +use once_cell::race::OnceBox as OnceLock; +#[cfg(feature = "std")] +use std::sync::OnceLock; + +#[cfg(feature = "std")] +use once_cell as _; /// Default G1 monomial bytes. const ETH_G1_MONOMIAL_POINTS: &[u8] = include_bytes!("./g1_monomial_bytes.bin"); @@ -9,31 +16,6 @@ const ETH_G1_LAGRANGE_POINTS: &[u8] = include_bytes!("./g1_lagrange_bytes.bin"); /// Default G2 monomial bytes. const ETH_G2_MONOMIAL_POINTS: &[u8] = include_bytes!("./g2_monomial_bytes.bin"); -macro_rules! create_cache { - ($name:ident) => { - static $name: OnceBox> = OnceBox::new(); - }; -} - -// We use separate OnceBox instances for each precompute value. -// This avoids the need for any unsafe code or mutexes. -create_cache!(CACHE_0); -create_cache!(CACHE_1); -create_cache!(CACHE_2); -create_cache!(CACHE_3); -create_cache!(CACHE_4); -create_cache!(CACHE_5); -create_cache!(CACHE_6); -create_cache!(CACHE_7); -create_cache!(CACHE_8); -create_cache!(CACHE_9); -create_cache!(CACHE_10); -create_cache!(CACHE_11); -create_cache!(CACHE_12); -create_cache!(CACHE_13); -create_cache!(CACHE_14); -create_cache!(CACHE_15); - /// Returns default Ethereum mainnet KZG settings. /// /// If you need a cloneable settings use `ethereum_kzg_settings_arc` instead. @@ -53,29 +35,14 @@ pub fn ethereum_kzg_settings_arc(precompute: u64) -> Arc { } fn ethereum_kzg_settings_inner(precompute: u64) -> &'static Arc { - let cache_box = match precompute { - 0 => &CACHE_0, - 1 => &CACHE_1, - 2 => &CACHE_2, - 3 => &CACHE_3, - 4 => &CACHE_4, - 5 => &CACHE_5, - 6 => &CACHE_6, - 7 => &CACHE_7, - 8 => &CACHE_8, - 9 => &CACHE_9, - 10 => &CACHE_10, - 11 => &CACHE_11, - 12 => &CACHE_12, - 13 => &CACHE_13, - 14 => &CACHE_14, - 15 => &CACHE_15, - _ => panic!( - "Unsupported precompute value: {precompute}. Only values 0-15 (inclusive) are supported." - ), - }; + static CACHES: [OnceLock>; 16] = [const { OnceLock::new() }; 16]; + + assert!( + precompute <= 15, + "Unsupported precompute value: {precompute}. Only values 0-15 (inclusive) are supported." + ); - cache_box.get_or_init(|| { + CACHES[precompute as usize].get_or_init(|| { let settings = KzgSettings::load_trusted_setup( ETH_G1_MONOMIAL_POINTS, ETH_G1_LAGRANGE_POINTS, @@ -83,7 +50,8 @@ fn ethereum_kzg_settings_inner(precompute: u64) -> &'static Arc { precompute, ) .expect("failed to load default trusted setup"); - Box::new(Arc::new(settings)) + #[allow(clippy::useless_conversion)] // `std`: no-op, `not(std)`: allocates into a `Box`. + Arc::new(settings).into() }) }