use std::any::Any;
use std::fmt::Debug;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use solverforge_core::score::Score;
use solverforge_core::ConstraintRef;
#[derive(Clone)]
pub struct EntityRef {
pub type_name: String,
pub display: String,
entity: Arc<dyn Any + Send + Sync>,
}
impl EntityRef {
pub fn new<T: Clone + Debug + Send + Sync + 'static>(entity: &T) -> Self {
Self {
type_name: std::any::type_name::<T>().to_string(),
display: format!("{:?}", entity),
entity: Arc::new(entity.clone()),
}
}
pub fn with_display<T: Clone + Send + Sync + 'static>(entity: &T, display: String) -> Self {
Self {
type_name: std::any::type_name::<T>().to_string(),
display,
entity: Arc::new(entity.clone()),
}
}
pub fn as_entity<T: 'static>(&self) -> Option<&T> {
self.entity.downcast_ref::<T>()
}
pub fn short_type_name(&self) -> &str {
self.type_name
.rsplit("::")
.next()
.unwrap_or(&self.type_name)
}
}
impl Debug for EntityRef {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("EntityRef")
.field("type", &self.short_type_name())
.field("display", &self.display)
.finish()
}
}
impl PartialEq for EntityRef {
fn eq(&self, other: &Self) -> bool {
self.type_name == other.type_name && self.display == other.display
}
}
impl Eq for EntityRef {}
impl Hash for EntityRef {
fn hash<H: Hasher>(&self, state: &mut H) {
self.type_name.hash(state);
self.display.hash(state);
}
}
#[derive(Debug, Clone)]
pub struct ConstraintJustification {
pub entities: Vec<EntityRef>,
pub description: String,
}
impl ConstraintJustification {
pub fn new(entities: Vec<EntityRef>) -> Self {
let description = if entities.is_empty() {
"No entities".to_string()
} else {
entities
.iter()
.map(|e| e.display.as_str())
.collect::<Vec<_>>()
.join(", ")
};
Self {
entities,
description,
}
}
pub fn with_description(entities: Vec<EntityRef>, description: String) -> Self {
Self {
entities,
description,
}
}
}
#[derive(Debug, Clone)]
pub struct DetailedConstraintMatch<'a, Sc: Score> {
pub constraint_ref: &'a ConstraintRef,
pub score: Sc,
pub justification: ConstraintJustification,
}
impl<'a, Sc: Score> DetailedConstraintMatch<'a, Sc> {
pub fn new(
constraint_ref: &'a ConstraintRef,
score: Sc,
justification: ConstraintJustification,
) -> Self {
Self {
constraint_ref,
score,
justification,
}
}
}
#[derive(Debug, Clone)]
pub struct ConstraintAnalysis<'a, Sc: Score> {
pub constraint_ref: &'a ConstraintRef,
pub weight_multiplier: u32,
pub score: Sc,
pub matches: Vec<DetailedConstraintMatch<'a, Sc>>,
pub is_hard: bool,
}
impl<'a, Sc: Score> ConstraintAnalysis<'a, Sc> {
pub fn new(
constraint_ref: &'a ConstraintRef,
weight_multiplier: u32,
score: Sc,
matches: Vec<DetailedConstraintMatch<'a, Sc>>,
is_hard: bool,
) -> Self {
Self {
constraint_ref,
weight_multiplier,
score,
matches,
is_hard,
}
}
pub fn match_count(&self) -> usize {
self.matches.len()
}
pub fn name(&self) -> &str {
&self.constraint_ref.name
}
}