|
| 1 | +use std::collections::{HashMap, HashSet}; |
| 2 | + |
| 3 | +use anyhow::Result; |
| 4 | +use turbo_tasks::{ValueToString, Vc}; |
| 5 | +use turbo_tasks_hash::hash_xxh3_hash64; |
| 6 | + |
| 7 | +use super::ModuleId; |
| 8 | +use crate::{ident::AssetIdent, module::Module}; |
| 9 | + |
1 | 10 | #[turbo_tasks::value]
|
2 | 11 | #[derive(Clone, Debug)]
|
3 |
| -pub struct GlobalInformation {} |
| 12 | +pub struct GlobalInformation { |
| 13 | + pub module_id_map: HashMap<AssetIdent, ModuleId>, |
| 14 | +} |
| 15 | + |
| 16 | +impl GlobalInformation { |
| 17 | + pub async fn get_module_id(&self, asset_ident: Vc<AssetIdent>) -> Result<Vc<ModuleId>> { |
| 18 | + let ident_str = asset_ident.to_string().await?; |
| 19 | + let ident = asset_ident.await?; |
| 20 | + let hashed_module_id = self.module_id_map.get(&ident); |
| 21 | + if let Some(hashed_module_id) = hashed_module_id { |
| 22 | + dbg!("Hashed module ID found", &ident_str, hashed_module_id); |
| 23 | + return Ok(hashed_module_id.clone().cell()); |
| 24 | + } |
| 25 | + dbg!("Hashed module ID not found", &ident_str); |
| 26 | + return Ok(ModuleId::String(ident_str.clone_value()).cell()); |
| 27 | + } |
| 28 | +} |
4 | 29 |
|
5 | 30 | #[turbo_tasks::value(transparent)]
|
6 | 31 | pub struct OptionGlobalInformation(Option<GlobalInformation>);
|
| 32 | + |
| 33 | +// NOTE(LichuAcu): This is a temporary location for this function, |
| 34 | +// it could later be moved to a `module_id_optimization.rs` file with |
| 35 | +// other module ID optimization logic. |
| 36 | +pub async fn process_module( |
| 37 | + module: Vc<Box<dyn Module>>, |
| 38 | + id_map: &mut HashMap<AssetIdent, ModuleId>, |
| 39 | + used_ids: &mut HashSet<u64>, |
| 40 | +) -> Result<()> { |
| 41 | + let ident = module.ident(); |
| 42 | + |
| 43 | + let hash = hash_xxh3_hash64(ident.to_string().await?); |
| 44 | + let mut masked_hash = hash & 0xF; |
| 45 | + let mut mask = 0xF; |
| 46 | + while used_ids.contains(&masked_hash) { |
| 47 | + if mask == 0xFFFFFFFFFFFFFFFF { |
| 48 | + return Err(anyhow::anyhow!("This is a... 64-bit hash collision?")); |
| 49 | + } |
| 50 | + mask = (mask << 4) | 0xF; |
| 51 | + masked_hash = hash & mask; |
| 52 | + } |
| 53 | + |
| 54 | + let hashed_module_id = ModuleId::String(masked_hash.to_string().into()); |
| 55 | + |
| 56 | + dbg!( |
| 57 | + "process_module", |
| 58 | + ident.await?.clone_value(), |
| 59 | + &hashed_module_id, |
| 60 | + mask |
| 61 | + ); |
| 62 | + |
| 63 | + id_map.insert(ident.await?.clone_value(), hashed_module_id); |
| 64 | + used_ids.insert(masked_hash); |
| 65 | + |
| 66 | + Ok(()) |
| 67 | +} |
0 commit comments