From ce8cabc3374b882af3646a4d0488599348b1891a Mon Sep 17 00:00:00 2001 From: Daniel Gulotta Date: Tue, 29 Jul 2025 13:23:08 -0700 Subject: [PATCH] remove some unsafe code (#366) This commit modifies the cache code to use Box::leak, eliminating the need for std::mem::transmute. --- src/backends/plonky2/circuits/utils.rs | 4 ++-- src/cache/mem.rs | 15 +++++---------- 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/src/backends/plonky2/circuits/utils.rs b/src/backends/plonky2/circuits/utils.rs index bd29127..65de60c 100644 --- a/src/backends/plonky2/circuits/utils.rs +++ b/src/backends/plonky2/circuits/utils.rs @@ -7,7 +7,7 @@ use plonky2::{ witness::{PartitionWitness, Witness}, }, plonk::circuit_data::CommonCircuitData, - util::serialization::{Buffer, IoResult, Read, Write}, + util::serialization::{Buffer, IoError, IoResult, Read, Write}, }; /// Plonky2 generator that allows debugging values assigned to targets. This generator doesn't @@ -66,7 +66,7 @@ impl, const D: usize> SimpleGenerator for Deb let name_len = src.read_usize()?; let mut name_buf = vec![0; name_len]; src.read_exact(&mut name_buf)?; - let name = unsafe { String::from_utf8_unchecked(name_buf) }; + let name = String::from_utf8(name_buf).map_err(|_| IoError)?; let xs = src.read_target_vec()?; Ok(Self { name, xs }) } diff --git a/src/cache/mem.rs b/src/cache/mem.rs index 6a3804b..af15b81 100644 --- a/src/cache/mem.rs +++ b/src/cache/mem.rs @@ -10,7 +10,7 @@ use serde::{de::DeserializeOwned, Serialize}; use sha2::{Digest, Sha256}; #[allow(clippy::type_complexity)] -static CACHE: LazyLock>>>> = +static CACHE: LazyLock>>> = LazyLock::new(|| Mutex::new(HashMap::new())); pub struct CacheEntry { @@ -28,7 +28,7 @@ impl Deref for CacheEntry { /// Get the artifact named `name` from the memory cache. If it doesn't exist, it will be built by /// calling `build_fn` and stored. /// The artifact is indexed by `params: P`. -pub(crate) fn get( +pub(crate) fn get( name: &str, params: &P, build_fn: fn(&P) -> T, @@ -43,14 +43,9 @@ pub(crate) fn get() { + if let Some(data) = (*boxed_data as &dyn Any).downcast_ref::() { log::debug!("found {} in the mem cache", name); - // The data is now in the heap (boxed), and will never go away because we can - // only insert into the CACHE if there's no entry, we can't delete nor update. - // Since it's not going away, not moving, and the CACHE is 'static, it's safe - // to extend the lifetime of data to 'static. - let data_static = unsafe { std::mem::transmute::<&T, &'static T>(data) }; - return Ok(CacheEntry { value: data_static }); + return Ok(CacheEntry { value: data }); } else { panic!( "type={} doesn't match the type in the cached boxed value with name={}", @@ -76,7 +71,7 @@ pub(crate) fn get