Skip to main content

solverforge_solver/heuristic/move/
swap.rs

1//! SwapMove - exchanges values between two entities.
2//!
3//! This move swaps the values of a planning variable between two entities.
4//! Useful for permutation-based problems.
5//!
6//! # Zero-Erasure Design
7//!
8//! SwapMove uses typed function pointers instead of `dyn Any` for complete
9//! compile-time type safety. No runtime type checks or downcasting.
10
11use std::fmt::Debug;
12
13use solverforge_core::domain::PlanningSolution;
14use solverforge_scoring::ScoreDirector;
15
16use super::Move;
17
18/// A move that swaps values between two entities.
19///
20/// Stores entity indices and typed function pointers for zero-erasure access.
21/// Undo is handled by `RecordingScoreDirector`, not by this move.
22///
23/// # Type Parameters
24/// * `S` - The planning solution type
25/// * `V` - The variable value type
26///
27/// # Example
28/// ```
29/// use solverforge_solver::heuristic::r#move::SwapMove;
30/// use solverforge_core::domain::PlanningSolution;
31/// use solverforge_core::score::SimpleScore;
32///
33/// #[derive(Clone)]
34/// struct Sol { values: Vec<Option<i32>>, score: Option<SimpleScore> }
35///
36/// impl PlanningSolution for Sol {
37///     type Score = SimpleScore;
38///     fn score(&self) -> Option<Self::Score> { self.score }
39///     fn set_score(&mut self, score: Option<Self::Score>) { self.score = score; }
40/// }
41///
42/// // Typed getter/setter with zero erasure
43/// fn get_v(s: &Sol, idx: usize) -> Option<i32> { s.values.get(idx).copied().flatten() }
44/// fn set_v(s: &mut Sol, idx: usize, v: Option<i32>) { if let Some(x) = s.values.get_mut(idx) { *x = v; } }
45///
46/// // Swap values between entities 0 and 1
47/// let swap = SwapMove::<Sol, i32>::new(0, 1, get_v, set_v, "value", 0);
48/// ```
49pub struct SwapMove<S, V> {
50    left_entity_index: usize,
51    right_entity_index: usize,
52    /// Typed getter function pointer - zero erasure.
53    getter: fn(&S, usize) -> Option<V>,
54    /// Typed setter function pointer - zero erasure.
55    setter: fn(&mut S, usize, Option<V>),
56    variable_name: &'static str,
57    descriptor_index: usize,
58    /// Store indices inline for entity_indices() to return a slice.
59    indices: [usize; 2],
60}
61
62impl<S, V> Clone for SwapMove<S, V> {
63    fn clone(&self) -> Self {
64        *self
65    }
66}
67
68impl<S, V> Copy for SwapMove<S, V> {}
69
70impl<S, V: Debug> Debug for SwapMove<S, V> {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        f.debug_struct("SwapMove")
73            .field("left_entity_index", &self.left_entity_index)
74            .field("right_entity_index", &self.right_entity_index)
75            .field("descriptor_index", &self.descriptor_index)
76            .field("variable_name", &self.variable_name)
77            .finish()
78    }
79}
80
81impl<S, V> SwapMove<S, V> {
82    /// Creates a new swap move with typed function pointers.
83    ///
84    /// # Arguments
85    /// * `left_entity_index` - Index of the first entity
86    /// * `right_entity_index` - Index of the second entity
87    /// * `getter` - Typed getter function pointer
88    /// * `setter` - Typed setter function pointer
89    /// * `variable_name` - Name of the variable being swapped
90    /// * `descriptor_index` - Index in the entity descriptor
91    pub fn new(
92        left_entity_index: usize,
93        right_entity_index: usize,
94        getter: fn(&S, usize) -> Option<V>,
95        setter: fn(&mut S, usize, Option<V>),
96        variable_name: &'static str,
97        descriptor_index: usize,
98    ) -> Self {
99        Self {
100            left_entity_index,
101            right_entity_index,
102            getter,
103            setter,
104            variable_name,
105            descriptor_index,
106            indices: [left_entity_index, right_entity_index],
107        }
108    }
109
110    /// Returns the left entity index.
111    pub fn left_entity_index(&self) -> usize {
112        self.left_entity_index
113    }
114
115    /// Returns the right entity index.
116    pub fn right_entity_index(&self) -> usize {
117        self.right_entity_index
118    }
119}
120
121impl<S, V> Move<S> for SwapMove<S, V>
122where
123    S: PlanningSolution,
124    V: Clone + PartialEq + Send + Sync + Debug + 'static,
125{
126    fn is_doable<D: ScoreDirector<S>>(&self, score_director: &D) -> bool {
127        // Can't swap with self
128        if self.left_entity_index == self.right_entity_index {
129            return false;
130        }
131
132        // Get current values using typed getter - zero erasure
133        let left_val = (self.getter)(score_director.working_solution(), self.left_entity_index);
134        let right_val = (self.getter)(score_director.working_solution(), self.right_entity_index);
135
136        // Swap only makes sense if values differ
137        left_val != right_val
138    }
139
140    fn do_move<D: ScoreDirector<S>>(&self, score_director: &mut D) {
141        // Get both values using typed getter - zero erasure
142        let left_value = (self.getter)(score_director.working_solution(), self.left_entity_index);
143        let right_value = (self.getter)(score_director.working_solution(), self.right_entity_index);
144
145        // Notify before changes
146        score_director.before_variable_changed(
147            self.descriptor_index,
148            self.left_entity_index,
149            self.variable_name,
150        );
151        score_director.before_variable_changed(
152            self.descriptor_index,
153            self.right_entity_index,
154            self.variable_name,
155        );
156
157        // Swap: left gets right's value, right gets left's value
158        (self.setter)(
159            score_director.working_solution_mut(),
160            self.left_entity_index,
161            right_value.clone(),
162        );
163        (self.setter)(
164            score_director.working_solution_mut(),
165            self.right_entity_index,
166            left_value.clone(),
167        );
168
169        // Notify after changes
170        score_director.after_variable_changed(
171            self.descriptor_index,
172            self.left_entity_index,
173            self.variable_name,
174        );
175        score_director.after_variable_changed(
176            self.descriptor_index,
177            self.right_entity_index,
178            self.variable_name,
179        );
180
181        // Register typed undo closure - swap back
182        let setter = self.setter;
183        let left_idx = self.left_entity_index;
184        let right_idx = self.right_entity_index;
185        score_director.register_undo(Box::new(move |s: &mut S| {
186            // Restore original values
187            setter(s, left_idx, left_value);
188            setter(s, right_idx, right_value);
189        }));
190    }
191
192    fn descriptor_index(&self) -> usize {
193        self.descriptor_index
194    }
195
196    fn entity_indices(&self) -> &[usize] {
197        &self.indices
198    }
199
200    fn variable_name(&self) -> &str {
201        self.variable_name
202    }
203}