diff --git a/crates/solverforge-core/WIREFRAME.md b/crates/solverforge-core/WIREFRAME.md index 8300a4ae..d4efdf6e 100644 --- a/crates/solverforge-core/WIREFRAME.md +++ b/crates/solverforge-core/WIREFRAME.md @@ -279,9 +279,7 @@ Constructors: `of([i64; H], [i64; S])`, `zero()`, `one_hard(usize)`, `one_soft(u Accessors: `hard_levels_count() -> usize`, `soft_levels_count() -> usize`, `hard_score(usize) -> i64`, `soft_score(usize) -> i64`, `hard_scores() -> &[i64; H]`, `soft_scores() -> &[i64; S]` -Implements: `Score`, `Ord`, `Copy`, `Eq`, `Hash`, `Default`, `Debug`, `Display` - -Does **not** implement `ParseableScore`. +Implements: `Score`, `ParseableScore`, `Ord`, `Copy`, `Eq`, `Hash`, `Default`, `Debug`, `Display` Optional: `serde::Serialize + Deserialize` (feature `serde`), hand-written in `score/bendable_serde.rs`: the wire shape is `{"hard": [...], "soft": [...]}`, and a level list whose length is not exactly `H` (or `S`) is rejected with an `invalid length` error. diff --git a/crates/solverforge-core/src/score/bendable.rs b/crates/solverforge-core/src/score/bendable.rs index cb5e6d2d..bfc8e840 100644 --- a/crates/solverforge-core/src/score/bendable.rs +++ b/crates/solverforge-core/src/score/bendable.rs @@ -6,7 +6,7 @@ use std::cmp::Ordering; use std::fmt; use std::ops::{Add, Neg, Sub}; -use super::traits::Score; +use super::traits::{ParseableScore, Score, ScoreParseError}; use super::ScoreLevel; /// A score with a configurable number of hard and soft levels. @@ -381,3 +381,61 @@ impl fmt::Display for BendableScore { ) } } + +/// Parses the `/`-separated levels inside one pair of brackets into exactly +/// `N` values; empty brackets hold zero levels. +fn parse_levels(text: &str, label: &str) -> Result<[i64; N], ScoreParseError> { + let parts: Vec<&str> = if text.trim().is_empty() { + Vec::new() + } else { + text.split('/').collect() + }; + if parts.len() != N { + return Err(ScoreParseError { + message: format!( + "BendableScore {} levels '[{}]': expected {} values, got {}", + label, + text, + N, + parts.len() + ), + }); + } + + let mut levels = [0; N]; + for (level, part) in levels.iter_mut().zip(parts) { + let part = part.trim(); + *level = part.parse::().map_err(|e| ScoreParseError { + message: format!("Invalid {} score '{}': {}", label, part, e), + })?; + } + Ok(levels) +} + +// BendableScore keeps its levels in brackets ("[0/-1]hard/[-5/0/7]soft"), so +// no macro. +impl ParseableScore for BendableScore { + fn parse(s: &str) -> Result { + let s = s.trim(); + + let (hard_str, soft_str) = s + .strip_prefix('[') + .and_then(|rest| rest.strip_suffix("]soft")) + .and_then(|rest| rest.split_once("]hard/[")) + .ok_or_else(|| ScoreParseError { + message: format!( + "Invalid BendableScore format '{}': expected '[X/...]hard/[Y/...]soft'", + s + ), + })?; + + Ok(BendableScore::of( + parse_levels(hard_str, "hard")?, + parse_levels(soft_str, "soft")?, + )) + } + + fn to_string_repr(&self) -> String { + format!("{}", self) + } +} diff --git a/crates/solverforge-core/src/score/tests/bendable_score.rs b/crates/solverforge-core/src/score/tests/bendable_score.rs index 059582bb..ae526774 100644 --- a/crates/solverforge-core/src/score/tests/bendable_score.rs +++ b/crates/solverforge-core/src/score/tests/bendable_score.rs @@ -85,3 +85,78 @@ fn test_level_number_out_of_range_panics() { let score: BendableScore<2, 3> = BendableScore::of([0, 0], [0, 0, 0]); let _ = score.level_number(5); } + +#[test] +fn test_parse() { + assert_eq!( + BendableScore::<2, 3>::parse("[0/-1]hard/[-5/0/7]soft").unwrap(), + BendableScore::of([0, -1], [-5, 0, 7]) + ); + assert_eq!( + BendableScore::<1, 2>::parse(" [ -1 ]hard/[ 0 / -5 ]soft ").unwrap(), + BendableScore::of([-1], [0, -5]) + ); + assert_eq!( + BendableScore::<0, 2>::parse("[]hard/[-1/-2]soft").unwrap(), + BendableScore::of([], [-1, -2]) + ); +} + +#[test] +fn test_display() { + let score: BendableScore<2, 3> = BendableScore::of([0, -1], [-5, 0, 7]); + assert_eq!(format!("{}", score), "[0/-1]hard/[-5/0/7]soft"); + assert_eq!(score.to_string_repr(), "[0/-1]hard/[-5/0/7]soft"); +} + +#[test] +fn display_then_parse_round_trips() { + for score in [ + BendableScore::<1, 3>::zero(), + BendableScore::of([-1000], [-2, 0, -123_456_789]), + BendableScore::of([i64::MIN], [i64::MAX, 1, -1]), + ] { + let text = score.to_string(); + assert_eq!(BendableScore::<1, 3>::parse(&text), Ok(score), "{text}"); + } +} + +#[test] +fn parse_rejects_a_wrong_number_of_levels() { + for (input, expected) in [ + ( + "[0]hard/[0/0/0]soft", + "hard levels '[0]': expected 2 values, got 1", + ), + ( + "[0/0]hard/[0/0/0/0]soft", + "soft levels '[0/0/0/0]': expected 3 values, got 4", + ), + ( + "[]hard/[0/0/0]soft", + "hard levels '[]': expected 2 values, got 0", + ), + ] { + let error = BendableScore::<2, 3>::parse(input).expect_err(input); + assert!(error.message.contains(expected), "{input}: {error}"); + } +} + +#[test] +fn parse_rejects_malformed_text() { + for input in [ + "", + "0hard/0soft", + "[0]hard", + "[0]soft/[0]hard", + "[0]hard/[0]soft/", + "[0]hard/[x]soft", + "[0.5]hard/[0]soft", + "[0]hard/[99999999999999999999]soft", + ] { + assert!( + BendableScore::<1, 1>::parse(input).is_err(), + "{input} must not parse" + ); + } +}