Skip to main content

solverforge_core/domain/
entity_ref.rs

1//! Entity reference types for dynamic entity access.
2//!
3//! These types enable the solver to work with entities at runtime without
4//! knowing their concrete types at compile time.
5
6use std::any::Any;
7use std::fmt::Debug;
8
9/// A reference to a planning entity with its index in the solution.
10///
11/// This struct provides a way to identify and access entities during solving
12/// without needing to know the concrete entity type.
13#[derive(Debug, Clone)]
14pub struct EntityRef {
15    /// Index of this entity in its collection.
16    pub index: usize,
17    /// Name of the entity type.
18    pub type_name: &'static str,
19    /// Name of the collection field in the solution.
20    pub collection_field: &'static str,
21}
22
23impl EntityRef {
24    /// Creates a reference to entity `index` of `type_name` in collection field `collection_field`.
25    pub fn new(index: usize, type_name: &'static str, collection_field: &'static str) -> Self {
26        Self {
27            index,
28            type_name,
29            collection_field,
30        }
31    }
32}
33
34/// Trait for extracting entities from a planning solution.
35///
36/// This trait is implemented by closures/functions that can extract
37/// entity references from a solution of a specific type.
38pub trait EntityExtractor: Send + Sync {
39    /// Number of entities in `solution`; `None` when `solution` is not the expected type.
40    fn count(&self, solution: &dyn Any) -> Option<usize>;
41
42    /// Borrows entity `index`; `None` on a solution type mismatch or when `index` is out of range.
43    fn get<'a>(&self, solution: &'a dyn Any, index: usize) -> Option<&'a dyn Any>;
44
45    /// Mutably borrows entity `index`; `None` on a solution type mismatch or
46    /// when `index` is out of range.
47    fn get_mut<'a>(&self, solution: &'a mut dyn Any, index: usize) -> Option<&'a mut dyn Any>;
48
49    /// Returns an iterator over entity references.
50    fn entity_refs(&self, solution: &dyn Any) -> Vec<EntityRef>;
51
52    /// Clone this extractor.
53    fn clone_box(&self) -> Box<dyn EntityExtractor>;
54
55    /// Clones an entity as a boxed value for insertion into the constraint session.
56    ///
57    /// This is used for incremental scoring where entities need to be inserted
58    /// into the BAVET session as owned, type-erased values.
59    fn clone_entity_boxed(
60        &self,
61        solution: &dyn Any,
62        index: usize,
63    ) -> Option<Box<dyn Any + Send + Sync>>;
64
65    /// `TypeId` of the extracted entity type.
66    fn entity_type_id(&self) -> std::any::TypeId;
67}
68
69impl Clone for Box<dyn EntityExtractor> {
70    fn clone(&self) -> Self {
71        self.clone_box()
72    }
73}
74
75/// A concrete entity extractor for a specific solution and entity type.
76///
77/// # Type Parameters
78/// * `S` - The solution type
79/// * `E` - The entity type
80pub struct EntityCollectionExtractor<S, E> {
81    // Name of the entity type.
82    type_name: &'static str,
83    // Name of the collection field in the solution.
84    collection_field: &'static str,
85    // Function to get the entity collection from a solution.
86    get_collection: fn(&S) -> &Vec<E>,
87    // Function to get the mutable entity collection from a solution.
88    get_collection_mut: fn(&mut S) -> &mut Vec<E>,
89}
90
91impl<S, E> EntityCollectionExtractor<S, E>
92where
93    S: 'static,
94    E: 'static,
95{
96    /// Creates an extractor from the collection's shared and mutable accessors.
97    pub fn new(
98        type_name: &'static str,
99        collection_field: &'static str,
100        get_collection: fn(&S) -> &Vec<E>,
101        get_collection_mut: fn(&mut S) -> &mut Vec<E>,
102    ) -> Self {
103        Self {
104            type_name,
105            collection_field,
106            get_collection,
107            get_collection_mut,
108        }
109    }
110}
111
112impl<S, E> EntityExtractor for EntityCollectionExtractor<S, E>
113where
114    S: Send + Sync + 'static,
115    E: Clone + Send + Sync + 'static,
116{
117    fn count(&self, solution: &dyn Any) -> Option<usize> {
118        let solution = solution.downcast_ref::<S>()?;
119        Some((self.get_collection)(solution).len())
120    }
121
122    fn get<'a>(&self, solution: &'a dyn Any, index: usize) -> Option<&'a dyn Any> {
123        let solution = solution.downcast_ref::<S>()?;
124        let collection = (self.get_collection)(solution);
125        collection.get(index).map(|e| e as &dyn Any)
126    }
127
128    fn get_mut<'a>(&self, solution: &'a mut dyn Any, index: usize) -> Option<&'a mut dyn Any> {
129        let solution = solution.downcast_mut::<S>()?;
130        let collection = (self.get_collection_mut)(solution);
131        collection.get_mut(index).map(|e| e as &mut dyn Any)
132    }
133
134    fn entity_refs(&self, solution: &dyn Any) -> Vec<EntityRef> {
135        let Some(solution) = solution.downcast_ref::<S>() else {
136            return Vec::new();
137        };
138        let collection = (self.get_collection)(solution);
139        (0..collection.len())
140            .map(|i| EntityRef::new(i, self.type_name, self.collection_field))
141            .collect()
142    }
143
144    fn clone_box(&self) -> Box<dyn EntityExtractor> {
145        Box::new(Self {
146            type_name: self.type_name,
147            collection_field: self.collection_field,
148            get_collection: self.get_collection,
149            get_collection_mut: self.get_collection_mut,
150        })
151    }
152
153    fn clone_entity_boxed(
154        &self,
155        solution: &dyn Any,
156        index: usize,
157    ) -> Option<Box<dyn Any + Send + Sync>> {
158        let solution = solution.downcast_ref::<S>()?;
159        let collection = (self.get_collection)(solution);
160        let entity = collection.get(index)?;
161        Some(Box::new(entity.clone()) as Box<dyn Any + Send + Sync>)
162    }
163
164    fn entity_type_id(&self) -> std::any::TypeId {
165        std::any::TypeId::of::<E>()
166    }
167}
168
169impl<S, E> Debug for EntityCollectionExtractor<S, E> {
170    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
171        f.debug_struct("EntityCollectionExtractor")
172            .field("type_name", &self.type_name)
173            .field("collection_field", &self.collection_field)
174            .finish()
175    }
176}