solverforge_core/score/
soft.rs1use std::cmp::Ordering;
4use std::fmt;
5
6use super::traits::{ParseableScore, Score, ScoreParseError};
7use super::ScoreLevel;
8
9#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27pub struct SoftScore {
28 score: i64,
29}
30
31impl SoftScore {
32 pub const ZERO: SoftScore = SoftScore { score: 0 };
34
35 pub const ONE: SoftScore = SoftScore { score: 1 };
37
38 #[inline]
40 pub const fn of(score: i64) -> Self {
41 SoftScore { score }
42 }
43
44 #[inline]
46 pub const fn score(&self) -> i64 {
47 self.score
48 }
49}
50
51impl Score for SoftScore {
52 #[inline]
53 fn is_feasible(&self) -> bool {
54 self.score >= 0
55 }
56
57 #[inline]
58 fn zero() -> Self {
59 SoftScore::ZERO
60 }
61
62 #[inline]
63 fn levels_count() -> usize {
64 1
65 }
66
67 #[inline]
68 fn level_number(&self, index: usize) -> i64 {
69 match index {
70 0 => self.score,
71 _ => panic!("SoftScore has 1 level, got index {}", index),
72 }
73 }
74
75 fn from_level_numbers(levels: &[i64]) -> Self {
76 assert_eq!(levels.len(), 1, "SoftScore requires exactly 1 level");
77 SoftScore::of(levels[0])
78 }
79
80 impl_score_scale!(SoftScore { score } => of);
81
82 fn level_label(index: usize) -> ScoreLevel {
83 match index {
84 0 => ScoreLevel::Soft,
85 _ => panic!("SoftScore has 1 level, got index {}", index),
86 }
87 }
88
89 #[inline]
90 fn to_scalar(&self) -> f64 {
91 self.score as f64
92 }
93}
94
95impl Ord for SoftScore {
96 fn cmp(&self, other: &Self) -> Ordering {
97 self.score.cmp(&other.score)
98 }
99}
100
101impl_score_ops!(SoftScore { score } => of);
102
103impl fmt::Debug for SoftScore {
104 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
105 write!(f, "SoftScore({})", self.score)
106 }
107}
108
109impl fmt::Display for SoftScore {
110 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
111 write!(f, "{}", self.score)
112 }
113}
114
115impl ParseableScore for SoftScore {
117 fn parse(s: &str) -> Result<Self, ScoreParseError> {
118 let s = s.trim();
119 let s = s.strip_suffix("init").unwrap_or(s);
121
122 s.parse::<i64>()
123 .map(SoftScore::of)
124 .map_err(|e| ScoreParseError {
125 message: format!("Invalid SoftScore '{}': {}", s, e),
126 })
127 }
128
129 fn to_string_repr(&self) -> String {
130 self.score.to_string()
131 }
132}
133
134impl From<i64> for SoftScore {
135 fn from(score: i64) -> Self {
136 SoftScore::of(score)
137 }
138}