solverforge_scoring/api/
weight_overrides.rs1use std::collections::HashMap;
6use std::fmt::Debug;
7use std::sync::Arc;
8
9use solverforge_core::Score;
10
11#[derive(Clone)]
16pub struct ConstraintWeightOverrides<Sc: Score> {
17 weights: HashMap<String, Sc>,
18}
19
20impl<Sc: Score> Debug for ConstraintWeightOverrides<Sc> {
21 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22 f.debug_struct("ConstraintWeightOverrides")
23 .field("count", &self.weights.len())
24 .finish()
25 }
26}
27
28impl<Sc: Score> Default for ConstraintWeightOverrides<Sc> {
29 fn default() -> Self {
30 Self::new()
31 }
32}
33
34impl<Sc: Score> ConstraintWeightOverrides<Sc> {
35 pub fn new() -> Self {
37 Self {
38 weights: HashMap::new(),
39 }
40 }
41
42 pub fn from_pairs<I, N>(iter: I) -> Self
44 where
45 I: IntoIterator<Item = (N, Sc)>,
46 N: Into<String>,
47 {
48 let weights = iter.into_iter().map(|(n, w)| (n.into(), w)).collect();
49 Self { weights }
50 }
51
52 pub fn put<N: Into<String>>(&mut self, name: N, weight: Sc) {
54 self.weights.insert(name.into(), weight);
55 }
56
57 pub fn remove(&mut self, name: &str) -> Option<Sc> {
59 self.weights.remove(name)
60 }
61
62 pub fn get_or_default(&self, name: &str, default: Sc) -> Sc {
64 self.weights.get(name).cloned().unwrap_or(default)
65 }
66
67 pub fn get(&self, name: &str) -> Option<&Sc> {
69 self.weights.get(name)
70 }
71
72 pub fn contains(&self, name: &str) -> bool {
74 self.weights.contains_key(name)
75 }
76
77 pub fn len(&self) -> usize {
79 self.weights.len()
80 }
81
82 pub fn is_empty(&self) -> bool {
84 self.weights.is_empty()
85 }
86
87 pub fn clear(&mut self) {
89 self.weights.clear();
90 }
91
92 pub fn into_arc(self) -> Arc<Self> {
94 Arc::new(self)
95 }
96}
97
98pub trait WeightProvider<Sc: Score>: Send + Sync {
101 fn weight(&self, name: &str) -> Option<Sc>;
103
104 fn weight_or_default(&self, name: &str, default: Sc) -> Sc {
106 self.weight(name).unwrap_or(default)
107 }
108}
109
110impl<Sc: Score> WeightProvider<Sc> for ConstraintWeightOverrides<Sc> {
111 fn weight(&self, name: &str) -> Option<Sc> {
112 self.get(name).cloned()
113 }
114}
115
116impl<Sc: Score> WeightProvider<Sc> for Arc<ConstraintWeightOverrides<Sc>> {
117 fn weight(&self, name: &str) -> Option<Sc> {
118 self.get(name).cloned()
119 }
120}