|
| 1 | +use crate::{ArtifactOutput, Compiler, CompilerSettings, Project}; |
| 2 | +use alloy_primitives::hex; |
| 3 | +use md5::Digest; |
| 4 | +use serde::{Deserialize, Serialize}; |
| 5 | + |
| 6 | +#[derive(Debug, Default)] |
| 7 | +pub struct CompilationProfiles<S> { |
| 8 | + profiles: Vec<CompilationProfile<S>>, |
| 9 | +} |
| 10 | + |
| 11 | +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 12 | +pub struct CompilationProfile<S> { |
| 13 | + pub settings: S, |
| 14 | + pub id: String, |
| 15 | +} |
| 16 | + |
| 17 | +impl<S: serde::Serialize> CompilationProfile<S> { |
| 18 | + pub fn new(settings: S) -> Self { |
| 19 | + let mut hasher = md5::Md5::new(); |
| 20 | + let ser = serde_json::to_string(&settings).unwrap(); |
| 21 | + hasher.update(ser.as_bytes()); |
| 22 | + let id = hex::encode(hasher.finalize()); |
| 23 | + |
| 24 | + Self { settings, id } |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +impl<S: CompilerSettings> CompilationProfiles<S> { |
| 29 | + pub fn new<C: Compiler<Settings = S>, T: ArtifactOutput>(project: &Project<C, T>) -> Self { |
| 30 | + let mut profiles = Self::default(); |
| 31 | + |
| 32 | + profiles.add(project.settings.clone()); |
| 33 | + |
| 34 | + profiles |
| 35 | + } |
| 36 | + |
| 37 | + pub fn add(&mut self, settings: S) -> usize { |
| 38 | + self.profiles.push(CompilationProfile::new(settings)); |
| 39 | + |
| 40 | + self.profiles.len() - 1 |
| 41 | + } |
| 42 | + |
| 43 | + pub fn find_or_create(&mut self, restrictions: &S::Restrictions) -> usize { |
| 44 | + if let Some((idx, _)) = self |
| 45 | + .profiles |
| 46 | + .iter() |
| 47 | + .enumerate() |
| 48 | + .find(|(_, profile)| profile.settings.satisfies_restrictions(restrictions)) |
| 49 | + { |
| 50 | + return idx; |
| 51 | + } |
| 52 | + |
| 53 | + self.add(self.profiles[0].settings.apply_restrictions(restrictions)) |
| 54 | + } |
| 55 | + |
| 56 | + pub fn get(&self, idx: usize) -> &CompilationProfile<S> { |
| 57 | + self.profiles.get(idx).unwrap() |
| 58 | + } |
| 59 | +} |
0 commit comments